UDP使用connect()和send()函数

UDP socket使用connect()函数连接服务器地址后,可直接调用send()函数发送数据,而不必像sendto()函数那样每次都要指定服务器地址,据说这样可以提高效率。

来写两个小程序玩玩:

client.cpp

#include 
#include 
#include 
#include 
#include 
#include 
#include 

int main()
{
	int sock;
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		printf("create socket failed: %d\n", errno);
		return -1;
	}
	
	struct sockaddr_in serveraddr;
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
	serveraddr.sin_port = htons(6666);
	
    // 调用connect指定服务器地址
	if (connect(sock, (struct sockaddr*)&serveraddr, sizeof(serveraddr)) == -1)
	{
		printf("connect failed: %d\n", errno);
		return -1;
	}
	
	int num = 0;
	char buffer[100] = {0};
	while (true)
	{
		snprintf(buffer, 99, "msg %d", ++num);
		send(sock, buffer, strlen(buffer), 0); // 直接send数据
		printf("send %s\n", buffer);
		sleep(1);
	}
	
	return 0;
}

server.cpp

#include 
#include 
#include 
#include 
#include 
#include 

#define MAX_BUFFER_LEN (8 * 1024)

int main()
{
	int sock;
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		printf("create socket failed: %d\n", errno);
		return -1;
	}
	
	struct sockaddr_in localaddr;
	localaddr.sin_family = AF_INET;
	localaddr.sin_addr.s_addr = INADDR_ANY;
	localaddr.sin_port = htons(6666);
	
	if (bind(sock, (const struct sockaddr *)&localaddr, sizeof(localaddr)) < 0)
	{
		printf("bind failed: %d\n", errno);
		return -1;
	}
	
	struct sockaddr_in clientaddr;
	int addrlen = sizeof(clientaddr);
	char buffer[MAX_BUFFER_LEN];
	while (true)
	{
		memset(buffer, 0, sizeof(buffer));
		int recvlen = recvfrom(sock, (char*)buffer, MAX_BUFFER_LEN, MSG_WAITALL, (struct sockaddr*)&clientaddr, (socklen_t*)&addrlen);
		printf("recv %s\n", buffer);
	}
	
	return 0;
}

运行结果:

UDP使用connect()和send()函数_第1张图片

UDP使用connect()和send()函数_第2张图片

 

 

 

你可能感兴趣的:(网络,udp,服务器,网络协议)