Home Operation and Maintenance Linux Operation and Maintenance How to implement select asynchronous communication under Linux

How to implement select asynchronous communication under Linux

May 15, 2023 am 09:28 AM
linux socket

1.Server side

/*select_server.c 2011.9.2 by yyg*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <pthread.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <unistd.h>

#define MAXBUF 1024

int main(int argc,char **argv){
  int sockfd,new_fd;
  socklen_t len;
  struct sockaddr_in my_addr,their_addr;
  unsigned int myport,lisnum;
  char buf[MAXBUF+1];
  fd_set rfds;
  struct timeval(argv[1]){
    myport = atoi(argv[1]);
  }
  else
    myport = 7838;

  if(argv[2]){
    lisnum = atoi(argv[2]);
  }
  else
    lisnum =2;
  if((sockfd = socket(PF_INET,SOCK_STREAM,0))== -1){
    perror("socket");
    exit(1);
  }

  bzero(&my_addr,sizeof(my_addr));
  my_addr.sin_family = PF_INET;
  my_addr.sin_port = htons(myport);
  if(argv[3])
    my_addr.sin_addr.s_addr = INADDR_ANY;
  
  if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr)) == -1){
    perror("bind");
    exit(1);
  }
  
  if(listen(sockfd, lisnum) == -1){
    perror("listen");
    exit(1);
  }
  
  while(1){
    printf("\n----waiting for new connecting to start new char----\n");
    len = sizeof(struct sockaddr);
    if((new_fd = accept(sockfd,(struct sockaddr *)&their_addr,&len)) == -1){
      perror("accept");
      exit(errno);
    }
    else
      printf("server:got connection from %s,port %d,socked %d\n",\
        inet_ntoa(their_addr.sin_addr),\
        ntohs(their_addr.sin_port),new_fd);
    
    /*开始处理每个新连接上的数据收发*/
    //printf("\n---ready to go.now you can chatting...input enter,then you can chat---\n");
    while(1){
      /*把集合清空*/
      FD_ZERO(&rfds);
      /*把标准输入句柄0加入到集合中*/
      FD_SET(0,&rfds);
      maxfd = 0;
      /*把当前连接句柄new_fd加入到集合中*/
      FD_SET(new_fd,&rfds);
      if(new_fd > maxfd)
        maxfd = new_fd;
      /*设置最大等待时间*/
      tv.tv_sec = 1;
      tv.tv_usec = 0;

      retval = select(maxfd+1,&rfds,NULL,NULL,&tv);
      if(retval == -1){
        printf("select error!%s\n",strerror(errno));
        break;
      }
      else if(retval == 0){
        //printf("no message come,user no press the button,please wait...\n");
        continue;
      }
      else{

        if(FD_ISSET(new_fd,&rfds)){
        /*连接的socket 上有消息则接收并显示*/
          bzero(buf,MAXBUF+1);
          /*接收对方发过来的消息,最多MAXBUF字节*/
          len = recv(new_fd, buf, MAXBUF, 0);
          if(len > 0)
            printf("recv msg success:%s! %d bytes rcv.\n ",buf,len);
          else{
            if(len < 0){
              printf("recv msg fail.the errno is:%d,error info is %s.\n",errno,strerror(errno));
            }
            else
              printf("quit.\n");
            break;
          }
        }// FD_ISSET = sockfd情况
        if(FD_ISSET(0,&rfds)){
          /*用户有输入了,则读取其内容并发送*/
          bzero(buf, MAXBUF+1);
          fgets(buf, MAXBUF, stdin);
          if(!strncasecmp(buf, "quit", 4)){
            printf("self request to quit the chating\n");
            break;
          }
          /*发消息给服务器*/
          len = send(new_fd, buf, strlen(buf)-1 , 0);
          if(len < 0){
            printf("mgs:%s send fail!errno is:%d,error info is:%s\n", buf, errno, strerror(errno));
            break;
          }else{
            printf("msg: %s\t send success, send %d bytes!\n", buf, len);
          }
        }//FD_ISSET = 0
      
      }//select 处理结束
      
    }/*内while*/
    close(new_fd);
    /*处理每个新连接上的数据收发结束*/
    printf("would you want to chatting with another one?(no->quit)");
    fflush(stdout);
    bzero(buf,MAXBUF+1);
    fgets(buf,MAXBUF,stdin);
    if(!strncasecmp(buf,"no",2)){
      printf("quit the chatting!\n");
      break;
    }
  
  }/*外while*/

  close(sockfd);
  return 0;
}
Copy after login

2.Client side

/*select_client.c 2011.9.2 by yyg*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <pthread.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <resolv.h>

#define MAXBUF 1024
int main(int argc,char **argv){
  int sockfd,len;
  struct sockaddr_in dest;
  char buffer[MAXBUF+1];
  fd_set rfds;
  struct timeval(argc != 3){
    printf("the param style wrong!\n");
    exit(0);
  }
  /*创建一个socket用于tcp通信*/
  if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0){
    perror("socket");
    exit(errno);
  }

  /*初始化服务器端(对方)的地址和端口信息*/
  bzero(&dest,sizeof(dest));
  dest.sin_family = AF_INET;
  dest.sin_port = htons(atoi(argv[2]));
  if(inet_aton(argv[1],(struct in_addr *)&dest.sin_addr.s_addr) == 0){
    perror(argv[1]);
    exit(errno);
  }

  /*conect to the server*/
  if(connect(sockfd,(struct sockaddr*)&dest,sizeof(dest)) !=0){
    perror("connect");
    exit(errno);
  }

  printf("\n---ready to chatting...---\n");
  while(1){
    /*把集合清空*/
    FD_ZERO(&rfds);
    /*把标准输入句柄0加入到集合中*/
    FD_SET(0,&rfds);
    maxfd = 0;
    /*把当前连接句柄socket 加入到集合中*/
    FD_SET(sockfd,&rfds);
    if(sockfd > maxfd)
      maxfd = sockfd;
    /*设置最大等待时间*/
    tv.tv_sec = 1;
    tv.tv_usec = 0;
    /*开始等待*/
    retval = select(maxfd+1,&rfds,NULL,NULL,&tv);
    if(retval == -1){
      printf("select error,quit!\n");
      break;
    }else if(retval == 0){
      continue;
    }else{
      if(FD_ISSET(sockfd,&rfds)){
        /*连接的socket 上有消息则接收并显示*/
        bzero(buffer,MAXBUF+1);
        /*接收对方发过来的消息,最多MAXBUF字节*/
        len = recv(sockfd, buffer, MAXBUF, 0);
        if(len > 0)
          printf("recv msg success:%s! %d bytes rcv.\n ",buffer,len);
        else{
          if(len < 0){
            printf("recv msg fail.the errno is:%d,error info is %s.\n",errno,strerror(errno));
          }
          else
            printf("quit.\n");
          break;
        }
      }// FD_ISSET = sockfd情况
      if(FD_ISSET(0,&rfds)){
        /*用户有输入了,则读取其内容并发送*/
        bzero(buffer, MAXBUF+1);
        fgets(buffer, MAXBUF, stdin);
        if(!strncasecmp(buffer, "quit", 4)){
          printf("self request to quit the chating\n");
          break;
        }
        /*发消息给服务器*/
        len = send(sockfd, buffer, strlen(buffer)-1 , 0);
        if(len < 0){
          printf("mgs:%s send fail!errno is:%d,error info is:%s\n", buffer, errno, strerror(errno));
          break;
        }else{
          printf("msg: %s\t send success, send %d bytes!\n", buffer, len);
        }
      }//FD_ISSET = 0
      
    }//select 处理结束

  }//处理聊天的while 循环
  /*关闭连接*/
  close(sockfd);
  return 0;
}
Copy after login

Running result:

Terminal 1: Server side

[root@localhost net]# ./select_server 7838

----waiting for new connecting to start new char----
server:got connection from 172.31.100.236,port 59462,socked 4
recv msg success:kfldsjfk! 8 bytes rcv.
456354
 msg: 456354
         send success, send 6 bytes!
recv msg success:453455! 6 bytes rcv.
Copy after login

Terminal 2: Client

[root@localhost net]#  ./select_client 172.31.100.236 7838

---ready to chatting...---
kfldsjfk
msg: kfldsjfk
         send success, send 8 bytes!
recv msg success:456354! 6 bytes rcv.
453455
 msg: 453455
         send success, send 6 bytes!
Copy after login

The above is the detailed content of How to implement select asynchronous communication under Linux. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Difference between centos and ubuntu Difference between centos and ubuntu Apr 14, 2025 pm 09:09 PM

The key differences between CentOS and Ubuntu are: origin (CentOS originates from Red Hat, for enterprises; Ubuntu originates from Debian, for individuals), package management (CentOS uses yum, focusing on stability; Ubuntu uses apt, for high update frequency), support cycle (CentOS provides 10 years of support, Ubuntu provides 5 years of LTS support), community support (CentOS focuses on stability, Ubuntu provides a wide range of tutorials and documents), uses (CentOS is biased towards servers, Ubuntu is suitable for servers and desktops), other differences include installation simplicity (CentOS is thin)

How to use docker desktop How to use docker desktop Apr 15, 2025 am 11:45 AM

How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

Centos options after stopping maintenance Centos options after stopping maintenance Apr 14, 2025 pm 08:51 PM

CentOS has been discontinued, alternatives include: 1. Rocky Linux (best compatibility); 2. AlmaLinux (compatible with CentOS); 3. Ubuntu Server (configuration required); 4. Red Hat Enterprise Linux (commercial version, paid license); 5. Oracle Linux (compatible with CentOS and RHEL). When migrating, considerations are: compatibility, availability, support, cost, and community support.

How to install centos How to install centos Apr 14, 2025 pm 09:03 PM

CentOS installation steps: Download the ISO image and burn bootable media; boot and select the installation source; select the language and keyboard layout; configure the network; partition the hard disk; set the system clock; create the root user; select the software package; start the installation; restart and boot from the hard disk after the installation is completed.

How to view the docker process How to view the docker process Apr 15, 2025 am 11:48 AM

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

What to do if the docker image fails What to do if the docker image fails Apr 15, 2025 am 11:21 AM

Troubleshooting steps for failed Docker image build: Check Dockerfile syntax and dependency version. Check if the build context contains the required source code and dependencies. View the build log for error details. Use the --target option to build a hierarchical phase to identify failure points. Make sure to use the latest version of Docker engine. Build the image with --t [image-name]:debug mode to debug the problem. Check disk space and make sure it is sufficient. Disable SELinux to prevent interference with the build process. Ask community platforms for help, provide Dockerfiles and build log descriptions for more specific suggestions.

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

See all articles