用socket实现基于udp的聊天

该程序比较简单,只能是一方发数据,另一方收数据
server.cpp


/*
服务器端
*/

#include 
#include

using namespace std;

#pragma comment(lib,"ws2_32.lib")

void main()
{
	WORD wVersionRequested;
	WSADATA wsaData;

	int err;
	wVersionRequested = MAKEWORD(1, 1);

	err = WSAStartup(wVersionRequested, &wsaData);
	if (err != 0) {


		return;
	}
	if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)

	{
		WSACleanup();
		return;
	}

	/////////////////////////////////////
	SOCKET sockSer;
	sockSer = socket(AF_INET, SOCK_DGRAM, 0);

	SOCKADDR_IN addrSer, addrCli;
	addrSer.sin_family = AF_INET;
	addrSer.sin_port = htons(4040);
	addrSer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

	bind(sockSer, (SOCKADDR*)&addrSer, sizeof(SOCKADDR));

	char sendbuf[256];
	char recvbuf[256];
	int len = sizeof(SOCKADDR);
	while (1)
	{
		recvfrom(sockSer, recvbuf, 256, 0,(SOCKADDR*)&addrCli,&len);
		cout << "Cli:>" << recvbuf << endl;

		cout << "Ser:>";
		cin >> sendbuf;
		if (strcmp(sendbuf, "quit") == 0) break;
		sendto(sockSer, sendbuf, strlen(sendbuf) + 1, 0, (SOCKADDR*)&addrCli, len);

	}
	closesocket(sockSer);

	WSACleanup();
}

client.cpp


/*
客户端
*/

#include 
#include

using namespace std;

#pragma comment(lib,"ws2_32.lib")

void main()
{

	WORD wVersionRequested;
	WSADATA wsaData;

	int err;
	wVersionRequested = MAKEWORD(1, 1);

	err = WSAStartup(wVersionRequested, &wsaData);
	if (err != 0) {


		return;
	}
	if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)

	{
		WSACleanup();
		return;
	}
	//////////////////////////////////////
	SOCKET sockCli;
	sockCli = socket(AF_INET, SOCK_DGRAM, 0);

	SOCKADDR_IN addrSer;
	addrSer.sin_family = AF_INET;
	addrSer.sin_port = htons(4040);
	addrSer.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");

	char sendbuf[256];
	char recvbuf[256];
	int len = sizeof(SOCKADDR);

	while (1)
	{
		cout << "Cli:>";
		cin >> sendbuf;
		if (strcmp(sendbuf,"quit")==0) break;
		sendto(sockCli, sendbuf, strlen(sendbuf) + 1, 0, (SOCKADDR*)&addrSer, len);
		recvfrom(sockCli, recvbuf, 256, 0, (SOCKADDR*)&addrSer, &len);
		cout << "Ser:>" << recvbuf << endl;
	}
	closesocket(sockCli);

	WSACleanup();
}

你可能感兴趣的:(C++)