Socket编程-回声客户端

所谓回声,是指客户端向服务器发送一条数据,服务器再原样返回给客户端,就像声音一样,遇到障碍物会反弹回来。

运行结果(客户端):

Socket编程-回声客户端_第1张图片

源代码:

服务器端:

#include 
#include 

#pragma comment(lib, "ws2_32.lib")   //加载 ws2_32.dll

const int BUFSIZE = 100;

int main()
{
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2,2), &wsaData);

	//创建套接字
	SOCKET servSock = socket(AF_INET, SOCK_STREAM, 0);
	
	//绑定套接字
	sockaddr_in servAddr;
	//每个字节都用0填充
	memset(&servAddr, 0, sizeof(servAddr));
	//使用IPv4地址
	servAddr.sin_family = AF_INET;
	//具体的IP地址
	servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
	//端口
	servAddr.sin_port = htons(1234);
	bind(servSock, (sockaddr *)&servAddr, sizeof(servAddr));

	//进入监听状态
	listen(servSock, 20);

	//接收客户端请求
	sockaddr clntAddr;
	int nSize = sizeof(sockaddr);
	SOCKET clntSock = accept(servSock, &clntAddr, &nSize);

	//缓冲区
	char buffer[BUFSIZE] = {0};
	//接收客户端发来的数据
	int strLen = recv(clntSock, buffer, BUFSIZE, 0);
	//将数据原样返回
	send(clntSock, buffer, strLen, 0);

	//关闭套接字
	closesocket(clntSock);
	closesocket(servSock);

	//终止 DLL 的使用
	WSACleanup();
	return 0;
}

客户端:

#include 
#include 

#pragma comment(lib, "ws2_32.lib")    //加载 ws2_32.dll

const int BUFSIZE = 100;

int main()
{
	//初始化DLL
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2,2), &wsaData);

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

	//向服务器发起请求
	sockaddr_in clntAddr;
	//每个字节都用0填充
	memset(&clntAddr, 0, sizeof(clntAddr));
	clntAddr.sin_family = AF_INET;
	clntAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
	clntAddr.sin_port = htons(1234);
	connect(clntSock, (sockaddr *)&clntAddr, sizeof(clntAddr));

	//获取用户输入的字符串并发送给服务器
	char sendBuf[BUFSIZE] = {0};
	printf("Input a string:");
	scanf("%s", sendBuf);
	send(clntSock, sendBuf, strlen(sendBuf), 0);

	//接收服务器传回的数据
	char recvBuf[BUFSIZE] = {0};
	recv(clntSock, recvBuf, BUFSIZE, 0);

	//输出接收到的数据
	printf("Message form server: %s\n", recvBuf);

	//关闭套接字
	closesocket(clntSock);
	
	//终止使用 DLL
	WSACleanup();

	system("pause");
	return 0;
}

 

你可能感兴趣的:(网络编程)