其他分享
首页 > 其他分享> > 用socket实现基于udp的聊天

用socket实现基于udp的聊天

作者:互联网

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


/*
服务器端
*/

#include <iostream>
#include<windows.h>

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 <iostream>
#include<windows.h>

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();
}

标签:SOCKADDR,udp,socket,addrSer,sendbuf,wsaData,聊天,sockSer,wVersionRequested
来源: https://blog.csdn.net/chenbiyun940419/article/details/95383113