1. 程式人生 > >linux c下簡單實現服務端與多客戶端同時連線

linux c下簡單實現服務端與多客戶端同時連線

參考文章:

http://blog.csdn.net/kangroger/article/details/41753605

http://www.cnblogs.com/xudong-bupt/archive/2013/12/29/3483059.html

       對於伺服器端來說,通過bind、listen,之後accept建立新的連線。accept返回的控制代碼建立的連線包括四部分:源IP、源埠號、目的IP、目的埠號。這樣在一個應用程式中,就算和多個客戶端建立連線,在收到資料後,應用程式通過目的IP和目的埠號也能區分是哪一條連線。

服務端:

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/shm.h>

#define PORT  8890
#define QUEUE_SIZE   10
#define BUFFER_SIZE 1024

void str_echo(int sockfd)  
{  
    char buffer[BUFFER_SIZE];
    pid_t pid = getpid();
    while(1)
    {
        memset(buffer,0,sizeof(buffer));
        int len = recv(sockfd, buffer, sizeof(buffer),0);
        if(strcmp(buffer,"exit\n")==0)
        {
	    printf("child process: %d exited.\n",pid);
            break;
        }
	printf("pid:%d receive:\n",pid);
        fputs(buffer, stdout);
        send(sockfd, buffer, len, 0);
    }
    close(sockfd);
}

int main(int argc, char **argv) 
{
    //定義IPV4的TCP連線的套接字描述符
    int server_sockfd = socket(AF_INET,SOCK_STREAM, 0);

    //定義sockaddr_in
    struct sockaddr_in server_sockaddr;
    server_sockaddr.sin_family = AF_INET;
    server_sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_sockaddr.sin_port = htons(PORT);

    //bind成功返回0,出錯返回-1
    if(bind(server_sockfd,(struct sockaddr *)&server_sockaddr,sizeof(server_sockaddr))==-1)
    {
        perror("bind");
        exit(1);//1為異常退出
    }
    printf("bind success.\n");  

    //listen成功返回0,出錯返回-1,允許同時幀聽的連線數為QUEUE_SIZE
    if(listen(server_sockfd,QUEUE_SIZE) == -1)
    {
        perror("listen");
        exit(1);
    }
    printf("listen success.\n");

    for(;;)
    {
        struct sockaddr_in client_addr;
        socklen_t length = sizeof(client_addr); 
        //程序阻塞在accept上,成功返回非負描述字,出錯返回-1
        int conn = accept(server_sockfd, (struct sockaddr*)&client_addr,&length); 
    	if(conn<0)
    	{
            perror("connect");
            exit(1);
    	}
        printf("new client accepted.\n");
        
        pid_t childid;
        if(childid=fork()==0)//子程序
        {
            printf("child process: %d created.\n", getpid());
            close(server_sockfd);//在子程序中關閉監聽  
            str_echo(conn);//處理監聽的連線  
            exit(0);
        }
    }

    printf("closed.\n");
    close(server_sockfd);
    return 0;
}

客戶端:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/shm.h>

#define PORT  8890
#define BUFFER_SIZE 1024

int main(int argc, char **argv)
{
    if(argc!=2)  
    {  
        printf("usage: client IP \n");  
        exit(0);  
    }

    //定義IPV4的TCP連線的套接字描述符
    int sock_cli = socket(AF_INET,SOCK_STREAM, 0);

    //定義sockaddr_in
    struct sockaddr_in servaddr;
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr(argv[1]);
    servaddr.sin_port = htons(PORT);  //伺服器埠
 
    //連線伺服器,成功返回0,錯誤返回-1
    if (connect(sock_cli, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
    {
        perror("connect");
        exit(1);
    }
    printf("connect server(IP:%s).\n",argv[1]);  

    char sendbuf[BUFFER_SIZE];
    char recvbuf[BUFFER_SIZE];
    //客戶端將控制檯輸入的資訊傳送給伺服器端,伺服器原樣返回資訊
    while (fgets(sendbuf, sizeof(sendbuf), stdin) != NULL)
    {
        send(sock_cli, sendbuf, strlen(sendbuf),0); ///傳送
        if(strcmp(sendbuf,"exit\n")==0)
        {
	    printf("client exited.\n");
            break;
        }
        printf("client receive:\n");
        recv(sock_cli, recvbuf, sizeof(recvbuf),0); ///接收
        fputs(recvbuf, stdout);

        memset(sendbuf, 0, sizeof(sendbuf));
        memset(recvbuf, 0, sizeof(recvbuf));
    }

    close(sock_cli);
    return 0;
}

server端起來後,埠情況如下:


client1和client2起來後,埠情況如下:


server執行情況如下:


client1執行情況如下:


client2執行情況如下: