Winodws实现基于UDP的简单聊天程序

客户端流程如下:

(1)创建套接字(socket)

(2)发送数据(sendto)

(3)关闭套接字

#include <WinSock2.h>
#include <stdio.h>
#pragma comment(lib,"WS2_32.lib")

int main()
{
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;
	wVersionRequested = MAKEWORD(1,1);
	err = WSAStartup(wVersionRequested,&wsaData);

	if(HIBYTE(wsaData.wVersion)!=1 && LOBYTE(wsaData.wVersion)!=1)
	{
		WSACleanup();
		return 0;
	}

	SOCKET socketClient = socket(AF_INET,SOCK_DGRAM,0);

	SOCKADDR_IN addrSrv;
	addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//输入为服务器端的IP
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_port = htons(6000);

	char recvBuf[100];
	char sendBuf[100];
	char tempBuf[100];

	int len = sizeof(SOCKADDR);

	while(1)
	{
		
		gets(sendBuf);
		printf("I say : %s\n",sendBuf);
		sendto(socketClient,sendBuf,strlen(sendBuf)+1,0,(SOCKADDR*)&addrSrv,len);

		recvfrom(socketClient,recvBuf,100,0,(SOCKADDR*)&addrSrv,&len);

		if(' '==recvBuf[0])
		{
			sendto(socketClient," ",strlen(" ")+1,0,(SOCKADDR*)&addrSrv,len);
			printf("Chat End!\n");
			break;
		}

		sprintf(tempBuf,"%s say: %s",inet_ntoa(addrSrv.sin_addr),recvBuf);
		printf("%s\n",tempBuf);
	}
	closesocket(socketClient);
	WSACleanup();
	getchar();
	return 0;
}

服务器端流程如下:

(1)创建套接字(socket)

(2)绑定套接字到一个本地地址和端口上(bind)

(3)接收数据(recvfrom)

(4)关闭套接字

#include <WinSock2.h>
#include <stdio.h>
#pragma comment(lib, "WS2_32.lib") 

int main()
{
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;

	wVersionRequested = MAKEWORD(1,1);

	err = WSAStartup(wVersionRequested,&wsaData);

	if(err!=0)
		return 0;

	if(LOBYTE(wsaData.wVersion) != 1 && HIBYTE(wsaData.wVersion)!=1)
	{
		WSACleanup();
		return 0;
	}

	SOCKET sockSrv = socket(AF_INET,SOCK_DGRAM,0);

	SOCKADDR_IN addrSrv;
	addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_port = htons(6000);

	bind(sockSrv,(SOCKADDR *)&addrSrv,sizeof(SOCKADDR));

	char recvBuf[100];
	char sendBuf[100];
	char tempBuf[100];

	SOCKADDR_IN addrClient;
	int len = sizeof(SOCKADDR);

	while(1)
	{
		recvfrom(sockSrv,recvBuf,100,0,(SOCKADDR*)&addrClient,&len);

		if(recvBuf[0] == ' ')
		{
			sendto(sockSrv," ",strlen(" ")+1,0,(SOCKADDR*)&addrClient,len);
			printf("Chat End!\n");
			break;
		}
		sprintf(tempBuf,"%s say : %s",inet_ntoa(addrClient.sin_addr),recvBuf);
		printf("%s\n",tempBuf);
		gets(sendBuf);
		printf("I say : %s\n",sendBuf);
		sendto(sockSrv,sendBuf,strlen(sendBuf)+1,0,(SOCKADDR*)&addrClient,len);
	}
	closesocket(sockSrv);
	WSACleanup();
	getchar();
	return 0;
}

客户端界面:

服务器端界面:

Winodws实现基于UDP的简单聊天程序_第1张图片


你可能感兴趣的:(Winodws实现基于UDP的简单聊天程序)