搜索
首页运维linux运维linux socket怎么实现使用线程独立收发消息

代码实现

1、服务器端

/*tcpserver.c  2011.9.1 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>

#define MYPORT 3490  //定义端口
#define BACKLOG 10
#define MAXDATASIZE 1024

int sockfd,new_fd;
pthread_t accthread,recthread;

void recmessage(void){  //接收客户端信息函数
  while(1){
    int numbytes;
    char buf[MAXDATASIZE];
    if((numbytes = recv(new_fd,buf,MAXDATASIZE,0))==-1){
      perror("recv");
      exit(1);
    }
    buf[numbytes]='\0';
    if(strcmp(buf,"exit")==0){  //若收到的是exit字符,则代表退出通信
      printf("Client is closed\n");
      close(new_fd);
      close(sockfd);
      exit(1);
    }
    printf("client:%s\n",buf);
  }/*while*/
}

void acceptconnect(void){  //接受客户端连接请求函数
  struct sockaddr_in their_addr;
  int sin_size;
  sin_size = sizeof(struct sockaddr_in);
  if((new_fd = accept(sockfd,(struct sockaddr *)&their_addr,&sin_size))==-1){
    perror("accept");
    exit(1);
  }
  printf("server:got connection from %s\n",inet_ntoa(their_addr.sin_addr));
  /*创建子线程,用于接收信息*/
  if((pthread_create(&recthread,NULL,(void*)recmessage,NULL)) != 0){
    printf("create thread error!\r\n");
    exit(1);
  }
}

int main(void){
  struct sockaddr_in my_addr;
  /*创建套接字*/
  if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1){
    perror("socket");
    exit(1);
  }
  /*初始化sockaddr_in结构体相关参数*/
  my_addr.sin_family = AF_INET;
  my_addr.sin_port = htons(MYPORT);
  my_addr.sin_addr.s_addr = INADDR_ANY;
  bzero(&(my_addr.sin_zero),8);

  /*绑定端口与套接字*/
  if(bind(sockfd,(struct sockaddr*)&my_addr,sizeof(struct sockaddr)) == -1){
    perror("bind");
    exit(1);
  }
  /*监听客户端套接字*/
  if(listen(sockfd,BACKLOG)== -1){
    perror("listen");
    exit(1);
  }
  printf("listening...\n");
  /*创建子线程,用于接收信息*/
  if((pthread_create(&accthread,NULL,(void*)acceptconnect,NULL))!=0){
    printf("create thread error!\n");
    exit(1);
  }
  while(1){
    char msg[MAXDATASIZE];
    scanf("%s",msg);
    if(send(new_fd,msg,strlen(msg),0) == -1){  //发送信息,与客户端交流
      perror("send");
      exit(1);
    }
    if(strcmp(msg,"exit") ==0){
      printf("byebye\n");
      close(new_fd);
      close(sockfd);
      exit(1);
    }
  }/*while*/
  return 0;
}/*main*/

2.客户端

/*tcpclient.c    2010.9.1 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 <netdb.h>

#define PORT 3490
#define BACKLOG 10
#define MAXDATASIZE 1024

int sockfd;
pthread_t recthread;

/*接收信息函数*/
void recmessage(void){
  while(1){
    int numbytes;
    char buf[MAXDATASIZE];
    
    if((numbytes = recv(sockfd,buf,MAXDATASIZE,0))==-1){
      perror("recv");
      exit(1);
    }
    buf[numbytes]='\0';
    if(strcmp(buf,"exit")==0){
      printf("Server is closed\n");
      close(sockfd);
      exit(1);
    }
    printf("Server:%s\n",buf);
  }/*while*/
}

int main(int argc,char *argv[]){
  struct hostent *he;
  struct sockaddr_in their_addr;
  /*客户端输入方式:./client 172.31.100.236,若无输入后面IP地址,会提示错误*/
  if(argc != 2){
    fprintf(stderr,"usage:client hostname\n");
    exit(1);
  }
  /*获取主机IP地址*/
  if((he = gethostbyname(argv[1])) == NULL){
    herror("gethostbyname");
    exit(1);
  }
  /*创建套接字*/
  if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1){
    perror("socket");
    exit(1);
  }
  /*初始化sockaddr_in结构体*/
  their_addr.sin_family = AF_INET;
  their_addr.sin_port = htons(PORT);
  their_addr.sin_addr = *((struct in_addr *)he->h_addr);
  bzero(&(their_addr.sin_zero),8);
  /*向服务器发送连接请求*/
  if(connect(sockfd,(struct sockaddr *)&their_addr,sizeof(struct sockaddr)) == -1){
    perror("connect");
    exit(1);
  }
  /*创建子线程,用于接收信息*/
  if((pthread_create(&recthread,NULL,(void*)recmessage,NULL))!= 0){
    printf("create thread error!\r\n");
    exit(1);
  }
  /*发送信息。接收发送信息用的是同一端口,都 是sockfd*/
  while(1){
    char msg[MAXDATASIZE];
    scanf("%s",msg);
    if(send(sockfd,msg,strlen(msg),0) == -1){
      perror("send");
      exit(1);
    }
    if(strcmp(msg,"exit") ==0){
      printf("byebye\n");
      close(sockfd);
      exit(1);
    }
  }/*while*/
  return 0;
}

运行结果:

终端1:

[root@localhost net]# ./tcpserver
server:got connection from 172.31.100.236
Hello,World! 
client:hello
client:xiaolian
client:iou
ok
exit
byebye

终端2:

[root@localhost net]# ./tcpclient 172.31.100.236
Server:Hello,World!
hello
xiaolian iou
Server:ok
Server is closed

以上是linux socket怎么实现使用线程独立收发消息的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:亿速云。如有侵权,请联系admin@php.cn删除
Linux操作:管理文件,目录和权限Linux操作:管理文件,目录和权限Apr 23, 2025 am 12:19 AM

在Linux中,文件和目录管理使用ls、cd、mkdir、rm、cp、mv命令,权限管理使用chmod、chown、chgrp命令。1.文件和目录管理命令如ls-l列出详细信息,mkdir-p递归创建目录。2.权限管理命令如chmod755file设置文件权限,chownuserfile改变文件所有者,chgrpgroupfile改变文件所属组。这些命令基于文件系统结构和用户、组系统,通过系统调用和元数据实现操作和控制。

Linux中的维护模式是什么?解释了Linux中的维护模式是什么?解释了Apr 22, 2025 am 12:06 AM

MaintenancemodeInuxisAspecialBootenvironmentforforcalsystemmaintenancetasks.itallowsadMinistratorStoperFormTaskSlikerSettingPassingPassingPasswords,RepairingFilesystems,andRecoveringFrombootFailuresFailuresFailuresInamInimAlenimalenimalenrenmentrent.ToEnterMainterMainterMaintErmaintErmaintEncemememodeBoode,Interlecttheboo

Linux:深入研究其基本部分Linux:深入研究其基本部分Apr 21, 2025 am 12:03 AM

Linux的核心组件包括内核、文件系统、Shell、用户空间与内核空间、设备驱动程序以及性能优化和最佳实践。1)内核是系统的核心,管理硬件、内存和进程。2)文件系统组织数据,支持多种类型如ext4、Btrfs和XFS。3)Shell是用户与系统交互的命令中心,支持脚本编写。4)用户空间与内核空间分离,确保系统稳定性。5)设备驱动程序连接硬件与操作系统。6)性能优化包括调整系统配置和遵循最佳实践。

Linux体系结构:揭示5个基本组件Linux体系结构:揭示5个基本组件Apr 20, 2025 am 12:04 AM

Linux系统的五个基本组件是:1.内核,2.系统库,3.系统实用程序,4.图形用户界面,5.应用程序。内核管理硬件资源,系统库提供预编译函数,系统实用程序用于系统管理,GUI提供可视化交互,应用程序利用这些组件实现功能。

Linux操作:利用维护模式Linux操作:利用维护模式Apr 19, 2025 am 12:08 AM

Linux的维护模式可以通过GRUB菜单进入,具体步骤为:1)在GRUB菜单中选择内核并按'e'编辑,2)在'linux'行末添加'single'或'1',3)按Ctrl X启动。维护模式提供了一个安全环境,适用于系统修复、重置密码和系统升级等任务。

Linux:如何进入恢复模式(和维护)Linux:如何进入恢复模式(和维护)Apr 18, 2025 am 12:05 AM

进入Linux恢复模式的步骤是:1.重启系统并按特定键进入GRUB菜单;2.选择带有(recoverymode)的选项;3.在恢复模式菜单中选择操作,如fsck或root。恢复模式允许你以单用户模式启动系统,进行文件系统检查和修复、编辑配置文件等操作,帮助解决系统问题。

Linux的基本要素:为初学者解释Linux的基本要素:为初学者解释Apr 17, 2025 am 12:08 AM

Linux的核心组件包括内核、文件系统、Shell和常用工具。1.内核管理硬件资源并提供基本服务。2.文件系统组织和存储数据。3.Shell是用户与系统交互的接口。4.常用工具帮助完成日常任务。

Linux:看看其基本结构Linux:看看其基本结构Apr 16, 2025 am 12:01 AM

Linux的基本结构包括内核、文件系统和Shell。1)内核管理硬件资源,使用uname-r查看版本。2)EXT4文件系统支持大文件和日志,使用mkfs.ext4创建。3)Shell如Bash提供命令行交互,使用ls-l列出文件。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!