linux网络编程之用多线程实现客户端到服务端的通信(基于udp)

102 阅读1分钟

1、开启一个线程接受数据,主线程发送数据的代码

 

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <netinet/in.h>
#include <errno.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/select.h>

//接收线程,负责消息并且显示
void *recv_thread(void* arg)
{
   int udp_fd = (int)arg;
   struct sockaddr_in addr;
   addr.sin_family = AF_INET;
   addr.sin_port = htons(8000);
   addr.sin_addr.s_addr = htonl(INADDR_ANY);

   socklen_t addrlen = sizeof(addr);
   bzero(&addr, sizeof(addr));
   while (1)
   {
       char buf[256] = "";
       char ipbuf[256] = "";
       recvfrom(udp_fd, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &addrlen);
       printf("\r\033[0:31m[%s]:\033[31m%s\n", inet_ntop(AF_INET, &addr.sin_addr, ipbuf, sizeo