TCP编程

tcp编程

简单的时间程序服务端

#include <stdio.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <time.h>
#include <unistd.h>
/*
并发服务
*/

int main(int argc, char * argv[]) {

    int sockfd,connfd;
    socklen_t len;
    struct sockaddr_in servaddr,clientaddr;
    char buff[1024];
    time_t ticks;
    pid_t pid;

    if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0){
        perror("socket");
        return -1;
    }

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(9111);
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if( bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        perror("bind");
        return -1;
    }
    printf("绑定端口成功\n");

    if(listen(sockfd, 2) < 0) {
        perror("listen");
        return -1;
    }
    printf("启动监听\n");

    while(1) {
        printf("等待Accept连接\n");
        len = sizeof(clientaddr);
        connfd = accept(sockfd, (struct sockaddr *)&clientaddr, &len);

        printf("接收到一个连接: %s, port %d\n", 
            inet_ntop(AF_INET, &clientaddr.sin_addr, buff, sizeof(buff)),
            ntohs(clientaddr.sin_port)
            );
        if((pid=fork()) == 0){
            close(sockfd);
            for(;;){
                ticks = time(NULL);
                snprintf(buff, sizeof(buff),"%.24s\r\n",ctime(&ticks));
                write(connfd, buff, strlen(buff));
                printf("发送时间成功, %s\n", ctime(&ticks));
                sleep(1);
            }
        }
        close(connfd);
    }
    return 0;
}
文档更新时间: 2021-03-01 14:42   作者:周国强