【Linux网络编程】基于UDP的客户端/服务器程序
程序员文章站
2022-06-06 08:44:08
...
效果就像开晚会的表白墙或者上墙一样,多个udp客户端都可以给服务端发送消息。
服务端代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
int main(int argc, char** argv)
{
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock < 0)
{
perror("socket");
return 1;
}
//bind
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_port = htons(atoi(argv[2]));
local.sin_addr.s_addr = inet_addr(argv[1]);
if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0 )
{
perror("bind");
return 2;
}
char buf[1024];
struct sockaddr_in remote;
socklen_t len = sizeof(remote);
while(1)
{
ssize_t s = recvfrom(sock, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&remote, &len);
if(s > 0)
{
buf[s] = 0;
printf("client %s : port %d : say# %s \n",inet_ntoa(remote.sin_addr), ntohs(remote.sin_port), buf);
sendto(sock, buf, strlen(buf),0,(struct sockaddr*)&remote, len);
}
else if( s == 0)
{
}
}
close(sock);
printf("server\n");
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
int main(int argc, char** argv)
{
// 1. new socket
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock < 0)
{
perror("socket");
return 1;
}
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2]));
server.sin_addr.s_addr = inet_addr(argv[1]);
char buf[1024];
socklen_t len = sizeof(server);
while(1)
{
printf("Please Enter #");
fflush(stdout);
ssize_t s = read(0, buf, sizeof(buf) - 1);
if(s > 0)
{
buf[s] = 0;
// send
sendto(sock, buf, strlen(buf),0,(struct sockaddr*)&server, len);
ssize_t _s = recvfrom(sock, buf, sizeof(buf) - 1, 0, NULL, NULL);
printf("server echo# %s\n", buf);
}
}
close(sock);
return 0;
}
截图:
服务端:
客户端A:
客户端B:
上一篇: 激光切割绘图编程软件