UDP协议实现交流通信
1.创建套接字
2.地址绑定
3.循环的接收消息和发送消息
4.关闭套接字
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <pthread.h>
void * fun(void * arg);
void * fun2(void * arg);
int main(int argc,char * argv[])
{
//创建套接字
int socketfd = socket(AF_INET,SOCK_DGRAM,0);
printf("当前套接字:%d\n",socketfd);
//填充地址结构体
char * des_ip ="10.9.71.155";
struct sockaddr_in my_add;
my_add.sin_family = AF_INET;
my_add.sin_port = htons(8000);
inet_pton(AF_INET,des_ip,(void *)&my_add.sin_addr);
//地址,IP进行绑定
bind(socketfd,(struct sockaddr *)&my_add,sizeof(my_add));
pthread_t pth,pth2;
//线程完成发送数据
pthread_create(&pth,NULL,fun,(void *)&socketfd);
pthread_create(&pth2,NULL,fun2,(void *)&socketfd);
//线程等待,这个也有缺陷,只能是一对一进行交流
pthread_join(pth,NULL);
pthread_join(pth2,NULL);
close(socketfd);
return 0;
}
void * fun(void * arg)
{
int socketfd = *(int*)arg;
while(1)
{
//循环发送消息
//填充要发送的地址结构体
char * des_ip ="10.9.71.137";
struct sockaddr_in to;
to.sin_family = AF_INET;
to.sin_port = htons(51431);
inet_pton(AF_INET,des_ip,(void *)&to.sin_addr);
//获取要发送的信息
char buf[128]= "";
fgets(buf,sizeof(buf),stdin);
//buf[strlen(buf)-1]=0;
//此步骤是将\n替换为‘\0’
//发送数据,前面的nun可以不要,如果后面没有使用,会有警告
ssize_t num = sendto(socketfd,buf,strlen(buf),0,(struct sockaddr *)&to,sizeof(to));
printf("发送了%ld个\n",num);
}
}
void * fun2(void * arg)
{
int socketfd = *(int*)arg;
while(1)
{
//提前定义一个结构体,用来保存接收到的消息
struct sockaddr_in from;
int len =sizeof(from);
char buff[1024] = "";
ssize_t num = recvfrom(socketfd,buff,sizeof(buff),0,(struct sockaddr *)&from,&len);
printf("读到了%ld个\n",num);
//unsigned char * ch = form.sin_addr;
printf("读到的内容为:%s\n",buff);
}
}