简体   繁体   English

如何在 C 中从服务器向客户端发送消息

[英]How to send a message from server to client in C

Hey guys I want to send a message of the current date from the server to a client in C.嘿伙计们,我想将当前日期的消息从服务器发送到 C 中的客户端。 So I would use a command like this for the client;所以我会为客户端使用这样的命令;

Terminal终端

telnet localhost PORT远程登录本地主机端口

What should be the command to send the actual message?发送实际消息的命令应该是什么?

int main(int argc, char *argv[])
{
    int socket_desc, client_sock, c, read_size;
    struct sockaddr_in server, client;
    char client_message[2000];
    time_t t = time(NULL);
    struct tm tm = *localtime(&t);

    
    socket_desc = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }

    
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(PORT);

    
    if (bind(socket_desc, (struct sockaddr *)&server, sizeof(server)) < 0)
    {
        
        perror("bind failed. Error");
        return 1;
    }

    
    listen(socket_desc, 3);
    
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);

    
    client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t *)&c);
    if (client_sock < 0)
    {
        perror("accept failed");
        return 1;
    }
    puts("Connection accepted");
    
////////////////////////////////////////////////////
        //the actual message here
////////////////////////////////////////////////////    
    close(socket_desc);

    return 0;
}

I made the following addiction and it worked我做了以下成瘾并且它起作用了

Is this a proper solution?这是一个适当的解决方案吗? I don't know how to use send() properly yet.我还不知道如何正确使用 send() 。

pid_t child_pid = fork();
if (child_pid == 0)
{
    snprintf(client_message, sizeof(client_message), "%s", ctime(&tick));
    write(client_sock, client_message, strlen(client_message));
    shutdown(client_sock, SHUT_RDWR);                                     
    while (read(client_sock, client_message, sizeof(client_message) > 0)) 
        close(client_sock);                                               
}
else if (child_pid > 0)
{
    // parent
    close(client_sock); 
}
else
{
    // a fork error occurred, handle and remember to close(connfd)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM