WinSocket实现基于TCP的对话

服务器端:

#include <stdio.h>
#include <Winsock2.h>

int 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 sockSrv = socket(AF_INET, SOCK_STREAM,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));
	// 将套接字设为监听模式,准备接收客户请求
	listen(sockSrv, 5);

	SOCKADDR_IN addrClient;
	int len = sizeof(SOCKADDR);

	while(1) {
		// 等待客户请求到来
		SOCKET sockConn = accept(sockSrv, (SOCKADDR*)&addrClient, &len);
		char sendBuf[100];
		// 将字符串写入sendBuf中
		sprintf(sendBuf, "Wellcome %s to http://www.sunxin.org", inet_ntoa(addrClient.sin_addr));
		// 发送数据
		send(sockConn, sendBuf, strlen(sendBuf)+1, 0);
		char recvBuf[100];
		// 接受数据
		recv(sockConn, recvBuf, 100, 0);
		// 打印接收的数据
		printf("%s\n", recvBuf);
		// 关闭套接字
		closesocket(sockConn);
	}
}


客户端:
#include <stdio.h>
#include <Winsock2.h>

int main() {
	// 加载套接字库
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;

	wVersionRequested = MAKEWORD(1,1);

	err = WSAStartup(wVersionRequested, &wsaData);
	if(err != 0) {
		return -1;
	}

	if(LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) {
		WSACleanup();
		return -2;
	}

	// 创建套接字
	SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);

	SOCKADDR_IN addrSrv;
	addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_port = htons(6000);
	// 向服务器发出连接请求
	connect(sockClient, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));

	// 接收数据
	char recvBuf[100];
	recv(sockClient, recvBuf, 100, 0);
	printf("%s\n", recvBuf);
	// 发出数据
	send(sockClient, "This is lisi", strlen("This is lisi")+1, 0);
	// 关闭套接字
	closesocket(sockClient);
	WSACleanup();

	getchar();
	return 0;
}

你可能感兴趣的:(C++,c,socket,C#)