网络示意图
不同于前面的TCP UDP 没有连接的概念 所以绑定以后不用侦听 直接收发就行 所以只需要开启一个服务器socket 就是 不需要对应的每个数据传输的socket
Socket_UDP 服务端逻辑
1 设置地址和选择协议IPV4/IPV6
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9876);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
2 初始好客户端的socket_in
struct sockaddr_in clientAddr;
int n;
int len = sizeof(clientAddr);
3 创建和绑定socket
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
printf("socket error.\n");
exit(1);
}
if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0)
{
printf("bind error.\n");
exit(1);
}
4 收发数据
while (1)
{
n = recvfrom(sock, buff_recv, 511, 0, (struct sockaddr *) &clientAddr, &len);
if (n > 0)
{
buff_recv[n] = 0;
printf("recv data from client:%s %u says: %s\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), buff_recv);
n = sendto(sock, buff_send, n, 0, (struct sockaddr *) &clientAddr, sizeof(clientAddr));
if (n < 0)
{
printf("sendto error.\n");
break;
}else {
printf("recv error.\n");
break;
}
}
return 0;
}
Socket_UDP 客户端逻辑
和TCP 相比少了connect 的概念
1 初始化各项操作 1目标地址 2buffer
struct sockaddr_in addr;
int sock;
addr.sin_family = AF_INET;
addr.sin_port = htons(9876);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2 初始化Socket
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
printf("socket error.\n");
exit(1);
}
if (addr.sin_addr.s_addr == INADDR_NONE)
{
printf("Incorrect ip address!");
close(sock);
exit(1);
}
3 收发消息
n = sendto(sock, buff_send, strlen(buff_send), 0, (struct sockaddr *) &addr, sizeof(addr));
if (n < 0)
{
printf("sendto error.\n");
close(sock);
}
n = recvfrom(sock, buff_recv, 512, 0, (struct sockaddr *) &addr, &len);
if (n > 0)
{
buff_recv[n] = 0;
printf("received from sever:");
puts(buff_recv);
}
|