C language Socket bi-directional communication + one service-side to the multi-client communication __c language

Source: Internet
Author: User
Tags socket error stdin strcmp server port htons
Task

After completing the socket client's communication to the server, let me do two-way communication, and then let me use the app to control the height and gpio of the mouth. Efforts for three days, from the socket learning to multithreading learning, step-by-Step completion of the task, Test the flow of data from app to server on the small board. Record it before work. Train of thought

Socket two-way communication using the method is a service-side open service and other client connections after a thread, and then the client socket CLIENT_SOCKFD passed through the input data sent to the client. and vice versa.
A server uses a select for multiple client communications. See the blog: http://blog.csdn.net/ctrl_qun/article/details/52524086 The author is very good, and the explanation is very comprehensive, Read on. A partial improvement was made to its code. Added to the client upload data to all clients, this is my project requirements. Then a header file is added. Because there are some out-of-the-box parameters that are initialized, you need to compile them using the C99 standard.

Gcc-std=c99 Client.c-o Client
bidirectional Communication
/* The code contains part of my driver control//*socket End/#include <stdio.h> #include <sys/types.h> #include <sys/socket.h > #include <netinet/in.h> #include <arpa/inet.h> #include <pthread.h> #include <stdlib.h> # Include <string.h> #include <linux/ioctl.h> #include <fcntl.h> #include <sys/stat.h> #define Maxbuf #define Dev_ioc_magic ' 0xEE '//define magic number #define Dev_iocprint _io (dev_ioc_magic, 1) #define Dev_io_high _io (DE
V_ioc_magic, 2) #define Dev_io_low _io (dev_ioc_magic, 3) #define DEV_IOC_MAXNR 3 char send_buf[maxbuf+1];
int FD;
    void *thread (void *x) {int cmd;
    Char Buf[bufsiz];
    int new_fd = * ((int*) x);
        while (recv (new_fd,buf,bufsiz,0) >0) {//int len=recv (new_fd,buf,bufsiz,0);
            if (strcmp (buf, "1") ==0) {printf ("<---call Dev_io_high--->\n");
            cmd = Dev_io_high; if (IOCTL (FD, CMD) < 0) {printf ("Call cmd Dev_io_higH fail\n ");
        printf ("Now,gpio is high.\n");
            } if (strcmp (buf, "0") ==0) {printf ("<---call Dev_io_low--->\n");
            cmd = Dev_io_low;
            if (IOCTL (FD, CMD) < 0) {printf ("Call cmd dev_io_low fail\n");
        printf ("Now,gpio is low.\n");
    printf ("client:received:%s\n", buf);
        }/*while (1) {bzero (send_buf, maxbuf + 1);
        scanf ("%s", send_buf); Send (NEW_FD, Send_buf, strlen (SEND_BUF), 0);  
Step 4th writes the string to the socket}*/return NULL;
    } void Open_dev () {fd = open ("/dev/dsx", O_RDWR);
if (FD < 0) printf ("/dev/dsx is open fail!\n");
    int main (int argc, char *argv[]) {int client_sockfd;
    int Len; struct sockaddr_in remote_addr;  Server-side network address structure Char Buf[bufsiz]; Buffer memset for data transfer (&AMP;REMOTE_ADDR,0,SIZEOF (REMOTE_ADDR)); Data initialization--Qing 0 remote_addr.sin_family=af_inet; Set to IPCommunication remote_addr.sin_addr.s_addr=inet_addr ("0.0.0.0");//server IP address remote_addr.sin_port=htons (8000);
    Server port number Open_dev (); /* Create client Socket--IPV4 protocol, connection-oriented communication, TCP protocol/if ((Client_sockfd=socket (pf_inet,sock_stream,0)) <0) {perror ("socket"
        );
    return 1; /* * Bind the socket to the server's network address/if (Connect (CLIENT_SOCKFD, (struct sockaddr *) &remote_addr,sizeof (struct sockaddr)) <0
        ) {perror ("connect");
    return 1;
    printf ("Connected to server\n");
    LEN=RECV (client_sockfd,buf,bufsiz,0),//Receiving server-side information//buf[len]= ' "; printf ("%s", buf);
    Print server-side information/create a new thread to send the operation.
    pthread_t Ntid;
    Pthread_create (&AMP;NTID,NULL,THREAD,&AMP;CLIENT_SOCKFD);
        /* Loop send receive information and print receive information--RECV returns the number of bytes received, send returns the number of bytes sent * * while (1) {//printf ("Enter string to send:");
        scanf ("%s", buf);
        if (!strcmp (buf, "quit")) break;
        Len=send (Client_sockfd,buf,strlen (BUF), 0); LEN=RECV (CLIENT_SOCKFD,BUF,BUFSIz,0);
        Buf[len]= ' ";
        printf ("received:%s\n", buf);
    printf ("Client:send ok.\n");
Close (CLIENT_SOCKFD);//Turn off socket return 0; }
/* Service End/#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h > #include <arpa/inet.h> #include <stdlib.h> #include <string.h> #define MAXBUF Recv_buf[ma Char
XBUF+1];
Char link_state=1;
int AA;
   void *fun (int x) {int new_fd=x;//(int) (* (int*) x));
     while (1) {bzero (recv_buf, maxbuf + 1);
     scanf ("%s", recv_buf);
     int len = Send (new_fd, recv_buf, sizeof (RECV_BUF), 0);
     printf ("Server:send ok\n");
   if (len<=0) break;
} exit (0);
    int main (int argc, char *argv[]) {int server_sockfd;//server-side socket int client_sockfd;//client socket int len;   struct sockaddr_in my_addr; The server network address structure body struct sockaddr_in remote_addr;
    The client network address structure body int sin_size;  Char Buf[bufsiz]; Buffer memset for data transfer (&AMP;MY_ADDR,0,SIZEOF (MY_ADDR)); Data initialization--Qing 0 my_addr.sin_family=af_inet; Set to IP Traffic my_addr.sin_addr.s_addr=inaddr_any;//server IP address--Allow connection to all local addresses my_addr.sin_port=hTons (8000);  
        Server port number/* Create server-side socket--IPV4 protocol, connection-oriented communication, TCP protocol/if ((Server_sockfd=socket (pf_inet,sock_stream,0)) <0) {
        Perror ("socket");
    return 1;
    /* Bind the socket to the server's network address */if (Bind (SERVER_SOCKFD, (struct sockaddr *) &my_addr,sizeof (struct sockaddr)) <0)
        {perror ("bind");
    return 1;

    /* Listen for connection request-the length of the listener queue is 5*/listen (server_sockfd,5);

    sin_size=sizeof (struct sockaddr_in); 
        /* Wait for client connection requests to reach/if ((Client_sockfd=accept (SERVER_SOCKFD, struct sockaddr *) &remote_addr,&sin_size) <0) {
        Perror ("accept");
    return 1;
    printf ("Accept client%s\n", Inet_ntoa (REMOTE_ADDR.SIN_ADDR));
    aa=client_sockfd;//can pass CLIENT_SOCKFD directly.
    Create a thread to send data to the client pthread_t Ntid;
    int a = Pthread_create (&AMP;NTID,NULL,FUN,AA); 
    if (a=0) printf ("ok\n"); /* Receive the client's data and send it to the client--RECV returns the number of bytes received, send returns the number of bytes sent * * while (recv (client_sockfd,buf,bufsiz,0)) >0) {printf (The server: recvived:%s\n ", buf);
    Close (CLIENT_SOCKFD);
        Close (SERVER_SOCKFD);
return 0; }
One service-side to multiple clients
/*client End/#include <stdio.h> #include <stdlib.h> #include <netinet/in.h> #include <sys/socket.h > #include <arpa/inet.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #i Nclude "client_gpio.h" #define BUFFER_SIZE 1024 int main (int argc, const char * argv[]) {struct sockaddr_in ser  
    VER_ADDR;  
    server_addr.sin_family = af_inet;  
    Server_addr.sin_port = htons (11332);  
    SERVER_ADDR.SIN_ADDR.S_ADDR = inet_addr ("0.0.0.0");  

    Bzero (& (Server_addr.sin_zero), 8);  
    int SERVER_SOCK_FD = socket (af_inet, sock_stream, 0);  
    if (server_sock_fd = = 1) {perror ("socket error");  
    return 1;  
    } Char Recv_msg[buffer_size];  

    Char Input_msg[buffer_size];  If Connect (server_sock_fd, (struct sockaddr *) &server_addr, sizeof (struct sockaddr_in)) = = 0) {Fd_set  
        Client_fd_set;  
        struct Timeval TV;
   Open_dev ();//Open the Drive device node. No delete     while (1) {tv.tv_sec = 20;  
            tv.tv_usec = 0;  
            Fd_zero (&client_fd_set);  
            Fd_set (Stdin_fileno, &client_fd_set);  

            Fd_set (SERVER_SOCK_FD, &client_fd_set);  
            Select (server_sock_fd + 1, &client_fd_set, NULL, NULL, &AMP;TV);  
                if (Fd_isset (Stdin_fileno, &client_fd_set)) {bzero (input_msg, buffer_size);  
                Fgets (Input_msg, Buffer_size, stdin);  
                if (Send (SERVER_SOCK_FD, input_msg, buffer_size, 0) = = 1) {perror ("Error sending message!\n");  
                } if (Fd_isset (SERVER_SOCK_FD, &client_fd_set)) {  
                Bzero (recv_msg, buffer_size);  
                Long Byte_num = recv (server_sock_fd, recv_msg, buffer_size, 0); if (Byte_num > 0) {if (Byte_num > Buffer_sizE) {byte_num = Buffer_size;
                    } Recv_msg[byte_num] = ';
                    if (strcmp (recv_msg, "open") ==0)//control the related functions of the device, you can delete {Set_gpio_high ();
                        } if (strcmp (recv_msg, "close") ==0)//control the related functions of the device, you can delete the {
                    Set_gpio_low ();  
                printf ("Server:%s\n", recv_msg);  
                else if (Byte_num < 0) {printf ("Accept message Error!\n");  
                    else {printf ("Server-side exit!\n");  
                Exit (0);  
return 0;  }
/*server End/#include <stdio.h> #include <stdlib.h> #include <netinet/in.h> #include <sys/socket.h > #include <arpa/inet.h> #include <string.h> #include <unistd.h> #include <sys/select.h> # Define BACKLOG 5//completion of three handshake but no accept queue Length #define CONCURRENT_MAX 8//The connection that the application layer can handle simultaneously #define SERVER_PORT 11332 #de  
Fine buffer_size 1024 #define QUIT_CMD ". QUIT" int Client_fds[concurrent_max];  
    int main (int argc, const char * argv[]) {char input_msg[buffer_size];  
    Char Recv_msg[buffer_size];  
    Local address struct sockaddr_in server_addr;  
    server_addr.sin_family = af_inet;  
    Server_addr.sin_port = htons (Server_port);  
    SERVER_ADDR.SIN_ADDR.S_ADDR = inet_addr ("0.0.0.0");  
    Bzero (& (Server_addr.sin_zero), 8);  
    Create a socket int server_sock_fd = socket (af_inet, sock_stream, 0);  
        if (server_sock_fd = = 1) {perror ("socket error");  
    return 1; }//Bind socket  
    int bind_result = bind (server_sock_fd, (struct sockaddr *) &server_addr, sizeof (SERVER_ADDR));  
        if (Bind_result = = 1) {perror ("bind error");  
    return 1;  
        //listen if (Listen (SERVER_SOCK_FD, BACKLOG) = = 1) {perror ("Listen error");  
    return 1;  
    }//fd_set fd_set Server_fd_set;  
    int max_fd =-1;  struct Timeval TV;  
        Timeout setting while (1) {tv.tv_sec = 20;  
        tv.tv_usec = 0;  
        Fd_zero (&server_fd_set);  
        Fd_set (Stdin_fileno, &server_fd_set);  
        if (max_fd <stdin_fileno) {max_fd = Stdin_fileno;  
    }//printf ("stdin_fileno=%d\n", Stdin_fileno);  
       Server-side socket Fd_set (SERVER_SOCK_FD, &server_fd_set);  
        printf ("server_sock_fd=%d\n", SERVER_SOCK_FD);  
        if (Max_fd < server_sock_fd) {max_fd = SERVER_SOCK_FD; }//GuestUser-side connection for (int i =0 i < Concurrent_max; i++) {//printf ("client_fds[%d]=%d\n", I, Clie  
            Nt_fds[i]);  
                if (Client_fds[i]!= 0) {fd_set (client_fds[i], &server_fd_set);  
                if (MAX_FD < client_fds[i]) {max_fd = client_fds[i];  
        int ret = SELECT (max_fd + 1, &server_fd_set, NULL, NULL, &AMP;TV);  
            if (Ret < 0) {perror ("select Error \ n");  
        Continue  
            else if (ret = 0) {printf ("Select timeout \ n");  
        Continue } else {//ret is the number of file descriptors that have changed without state if Fd_isset (Stdin_fileno, &server_fd_  
                Set)) {printf ("Send message: \ n");  
                Bzero (input_msg, buffer_size);  
Fgets (Input_msg, Buffer_size, stdin);                Enter ". Quit" to exit the server if (strcmp (input_msg, quit_cmd) = = 0) {  
                Exit (0); for (int i = 0; i < Concurrent_max i++) {if (client_fds[i)  
                        != 0) {printf ("client_fds[%d]=%d\n", I, client_fds[i]);  
                    Send (Client_fds[i], input_msg, buffer_size, 0);  
                }} if (Fd_isset (SERVER_SOCK_FD, &server_fd_set)) {  
                There is a new connection request struct sockaddr_in client_address;  
                Socklen_t Address_len;  
                int client_sock_fd = Accept (server_sock_fd, (struct sockaddr *) &client_address, &address_len);  
                printf ("New Connection client_sock_fd =%d\n", client_sock_fd);  
           if (client_sock_fd > 0) {         int index =-1;  
                        for (int i = 0; i < Concurrent_max i++) {if (client_fds[i) = = 0)  
                            {index = i;  
                            Client_fds[i] = CLIENT_SOCK_FD;  
                        Break } if (index >= 0) {printf  
                    ("New Client (%d) join successful%s:%d\n", Index, Inet_ntoa (CLIENT_ADDRESS.SIN_ADDR), Ntohs (Client_address.sin_port));  
                        else {bzero (input_msg, buffer_size);  
                        strcpy (input_msg, "server joined the maximum number of clients, can not join the!\n");  
                        Send (CLIENT_SOCK_FD, input_msg, buffer_size, 0);  
     printf ("Maximum number of client connections reached, new client joins failed%s:%d\n", Inet_ntoa (CLIENT_ADDRESS.SIN_ADDR), Ntohs (Client_address.sin_port));               for (int i =0 i < Concurrent_max; i++) {if (Client_fds[i]!=0) {if (Fd_isset (client_fds[i), &serve R_fd_set) {//processing a message from a client bzero (recv_msg, BUFF  
                        Er_size);  
                        Long Byte_num = recv (Client_fds[i], recv_msg, buffer_size, 0);  
                            if (Byte_num > 0) {if (Byte_num > Buffer_size)  
                            {byte_num = buffer_size;  
                            }//recv_msg[byte_num] = ';
                            printf ("Client (%d):%s", I, recv_msg);  
            /* Forwarding data to other clients * * for (int i = 0; i < Concurrent_max i++)                {if (Client_fds[i]!= 0) {  
                                Send (Client_fds[i], recv_msg, sizeof (RECV_MSG), 0);  
                        }///End Forwarding content */}  
                        else if (Byte_num < 0) {printf ("Error accepting message from client (%d). \ n", i); else {FD_CL  
                            R (Client_fds[i], &server_fd_set);  
                            Client_fds[i] = 0;  
                        printf ("Client (%d) exited \ n", i); }}}}} return<

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.