用Socket实现基于TCP的聊天

程序比较简单,在一个时刻只能有端能发数据,另一方接受数据
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, addrCli;//定义一个套接字
	sockSer = socket(AF_INET, SOCK_STREAM, 0);//参数说明:IP家族协议、流式套接字、默认参数

	SOCKADDR_IN addrSer;//定义服务器的地址
	addrSer.sin_family = AF_INET;//协议
	addrSer.sin_port = htons(5050);//端口
	addrSer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//服务端的IP地址

	bind(sockSer, (SOCKADDR*)&addrSer, sizeof(SOCKADDR));//将服务器的地址信息和套接字进行绑定

	listen(sockSer, 5);//进行监听,队列长度为5个字节

	SOCKET sockConn;//定义连接套接字
	int len = sizeof(SOCKADDR);

	cout << "Server Wait Client Connect....." << endl;
	sockConn = accept(sockSer, (SOCKADDR*)&addrCli, &len);//接受请求
	if (sockConn == INVALID_SOCKET)
	{
		cout << "Server Accept Client Connect Fail!" << endl;
		return;
	}
	else
	{
		cout << "Server Accept Client Connect Success!" << endl;
	}

	char sendbuf[256];
	char recvbuf[256];
	while (1)
	{
		cout << "Ser:>";
		cin >> sendbuf;
		if (strcmp(sendbuf, "quit") == 0)
		{
			break;
		}

		send(sockConn,sendbuf,strlen(sendbuf)+1,0);//发送数据
		recv(sockConn,recvbuf,256,0);//接受数据
		cout << "Cli:>" << recvbuf << endl;
	}
	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_STREAM, 0);
	SOCKADDR_IN addrSer;
	addrSer.sin_family = AF_INET;
	addrSer.sin_port = htons(5050);
	addrSer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

	int res=connect(sockCli,(SOCKADDR*)&addrSer,sizeof(SOCKADDR));
	if (res != 0)
	{
		cout << "Client Connect Server Fail!" << endl;
		return;
	}
	else
	{
		cout << "Client Connect Server Success!" << endl;
	}

	char sendbuf[256];
	char recvbuf[256];
	while (1)
	{
		recv(sockCli, recvbuf, 256,0);
		cout << "Ser:>" << recvbuf << endl;

		cout << "Cli:>";
		cin >> sendbuf;
		if (strcmp(sendbuf, "quit") == 0)
		{
			break;
		}
		send(sockCli, sendbuf, strlen(sendbuf) + 1,0);
	}
	closesocket(sockCli);


	WSACleanup();
}

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