欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UDP实现网络通信(客户端和服务端)

程序员文章站 2022-03-16 11:23:45
...

内容简介

主要通过UDP实现客户端和服务端的通信,程序主要包括Server.c和Client.c.执行流程为:先启动服务端,然后在启动客户端,客户端向服务端发送消息,服务端收到后给客户端回消息,这样一发一回进行客户端和服务端的交互。

代码

Server.c

#include<WinSock2.h>
#include<stdio.h>
#pragma warning(disable:4996)
#pragma comment(lib,"ws2_32.lib")
#define BUFFER_SIZE 1024
#define PORT 6000
int main()
{
	WSADATA WSAData;
	char receBuf[BUFFER_SIZE];
	if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0)
	{
		printf("初始化失败");
		return -1;
	}
	SOCKET sockServer = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (sockServer == INVALID_SOCKET)
	{
		printf("Faile socket()\n");
		return -2;
	}
	SOCKADDR_IN addr_Server;
	addr_Server.sin_family = AF_INET;
	addr_Server.sin_port = htons(PORT);
	addr_Server.sin_addr.S_un.S_addr = INADDR_ANY;
	if (bind(sockServer, (SOCKADDR*)&addr_Server, sizeof(addr_Server)) == SOCKET_ERROR)
	{
		printf("Failed socket()%d\n", WSAGetLastError());
		return 0;
	}
	SOCKADDR_IN addr_Client;
	int addr_ClientLen = sizeof(SOCKADDR);
	while (TRUE)
	{
		int last =recvfrom(sockServer, receBuf, sizeof(receBuf), 0, (SOCKADDR*)&addr_Client, &addr_ClientLen);
		receBuf[last] = '\0';
		printf("接收到数据(%s):%s\n", inet_ntoa(addr_Client.sin_addr), receBuf);
		memset(receBuf, 0, sizeof(receBuf));
		printf("Please input send content: ");
		scanf("%s", receBuf);
		sendto(sockServer, receBuf, strlen(receBuf), 0, (SOCKADDR*)&addr_Client, sizeof(SOCKADDR));
		memset(receBuf, 0, strlen(receBuf));
	}
	closesocket(sockServer);
	WSACleanup();
	return 0;
}

Client.c

#include<stdio.h>
#include<winsock2.h>
#include<string.h>
//#include<Windows.h>
#pragma comment(lib,"ws2_32.lib")
#pragma warning(disable:4996)
#define BUFFER_SIZE 10240
#define PORT 6000
int main(int argc, const char*argv[])
{
	char receBuf[BUFFER_SIZE];
	char sendBuf[BUFFER_SIZE];
	//初始化网络环境
	WSADATA wsa;
	if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
	{
		printf("WSAStartup failed\n");
		return -1;
	}
	SOCKET sock_Client = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if(sock_Client == INVALID_SOCKET)
	{
		printf("create socket failed\n");
		return -1;
	}
	//绑定地址信息
	SOCKADDR_IN serverAddr;
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(PORT);
	serverAddr.sin_addr.S_un.S_addr =inet_addr("127.0.0.1");
	SOCKADDR_IN clientAddr;
	int clientLen = sizeof(clientAddr);
	while (TRUE)
	{
		printf("Please input send content: ");
		scanf("%s", sendBuf);
		sendto(sock_Client, sendBuf, strlen(sendBuf), 0, (SOCKADDR*)&serverAddr, sizeof(SOCKADDR));
		memset(sendBuf, 0, sizeof(sendBuf));
		int last = recvfrom(sock_Client, receBuf, sizeof(receBuf), 0, (SOCKADDR*)&clientAddr, &clientLen);
		if (last == 0)
		{
			printf("recv failed\n");
		}
		receBuf[last] = '\0';
		printf("recvfrom=%s\n",receBuf);
		memset(receBuf, 0, sizeof(receBuf));
	}
	closesocket(sock_Client);
	WSACleanup();
	return 0;
}

运行结果

UDP实现网络通信(客户端和服务端)

相关标签: UDP 网络通信