流式套接字——简单的回射服务器示例

文章目录

    • Server
    • Client

Server

#define WIN32_LEAN_AND_MEAN
#include 
#include 
#include 
#include 
#include 

#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main(int argc, char **argv) 
{
	WSADATA wsaData;
	int iResult;
	SOCKET ListenSocket = INVALID_SOCKET;
	SOCKET ClientSocket = INVALID_SOCKET; 
	struct addrinfo *result = NULL;
	struct addrinfo hints;
	int iSendResult; 
	char recvbuf[DEFAULT_BUFLEN];
	int recvbuflen = DEFAULT_BUFLEN;
	//初始化WinSock
	iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); 
	if(iResult != 0) {
		printf("WSAStartup failed with error: %d\n", iResult);
		return 1;
	}
	ZeroMemory(&hints, sizeof(hints));
	//声明IPV4地址族,流式套接字,TCP协议
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	//解析服务器地址和端口号
	iResult = getaddrinfo("192.168.42.166", DEFAULT_PORT, &hints, &result);
	if(iResult != 0) {
		printf("getaddrinfo failed with error: %d\n", iResult);
		WSACleanup();
		return 1;
	}

	//为面向连接的服务器创建套接字
	ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
	if(ListenSocket == INVALID_SOCKET) {
		printf("socket failed with error: %ld\n", WSAGetLastError());
		freeaddrinfo(result);
		WSACleanup();
		return 1;
	}

	//为监听套接字绑定本地地址和端口号 
	iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
	if(iResult == SOCKET_ERROR) {
		printf("bind failed with error: %d\n", WSAGetLastError());
		freeaddrinfo(result);
		WSACleanup();
		return 1;
	}
	freeaddrinfo(result);

	//在监听套接字上等待连接请求
	if(listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) {
		printf("listen failed with error: %d\n", WSAGetLastError());
		closesocket(ListenSocket);
		WSACleanup();
		return 1;
	}
	printf("TCP server starting...\n");
	//接受客户端的请求连接
	ClientSocket = accept(ListenSocket, NULL, NULL);
	if(ClientSocket == INVALID_SOCKET) {
		printf("accept failed: %d\n", WSAGetLastError());
		closesocket(ClientSocket);
		WSACleanup();
		return 1;	
	}
	closesocket(ListenSocket);
	
	//持续接收数据,直到对方关闭连接
	do {
		iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
		if(iResult > 0) {
			//情况1:成功接收到数据
			printf("Bytes received: %d\n", iResult);
			//将缓冲区的内容回送给客户端
			iSendResult = send(ClientSocket, recvbuf, iResult, 0);
			if(iSendResult == SOCKET_ERROR){
				printf("send failed with error: %d\n", WSAGetLastError());
				closesocket(ClientSocket);
				WSACleanup();
				return 1;
			}
			printf("Bytes sent: %d\n", iSendResult);
		}
		else if(iResult == 0) 
			//情况2:关闭连接
			printf("Connection closing...\n");
		else {
			//情况3:接收发生错误
			printf("recv failed with error: %d\n", WSAGetLastError());
			closesocket(ClientSocket);
			WSACleanup();
			return 1;
		}
	}while(iResult > 0);
	//关闭连接
	iResult = shutdown(ClientSocket, SD_SEND);
	if(iResult == SOCKET_ERROR) {
		printf("shutdown failed with error: %d\n", WSAGetLastError());
		closesocket(ClientSocket);
		WSACleanup();
		return 1;
	}
	//关闭套接字
	closesocket(ClientSocket);
	//释放资源
	WSACleanup();
	return 0;
}

Client

#define WIN32_LEAN_AND_MEAN
#include 
#include 
#include 
#include 
#include 

#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main(int argc, char **argv) 
{
	WSADATA wsaData;
	SOCKET ConnectSocket = INVALID_SOCKET;
	struct addrinfo *result = NULL, *ptr = NULL, hints ;
	char *sendbuf = "this is a test";
	char recvbuf[DEFAULT_BUFLEN];
	int iResult;
	int recvbuflen = DEFAULT_BUFLEN;
	if(argc != 2) {
		printf("usage: %s server-name\n", argv[0]);
		return 1;
	}

	//初始化套接字
	iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if(iResult != 0) {
		printf("WSAStartup failed with error: %d\n", iResult);
		return 1;
	}
	ZeroMemory(&hints, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	//解析服务器地址和端口号
	iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
	if(iResult != 0) {
		printf("getaddrinfo failed with error: %d\n", iResult);
		WSACleanup();
		return 1;
	}
	//尝试连接服务器地址,直到成功
	for(ptr = result; ptr != NULL; ptr = ptr->ai_next) {
		//创建套接字
		ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
		if(ConnectSocket == INVALID_SOCKET) {
			printf("socket failed with error: %ld\n", WSAGetLastError());
			WSACleanup();
			return 1;
		}
		//向服务器请求连接
		iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
		if(iResult == SOCKET_ERROR) {
			closesocket(ConnectSocket);
			ConnectSocket = INVALID_SOCKET;
			continue;
		}
		break;
	}
	freeaddrinfo(result);
	if(ConnectSocket == INVALID_SOCKET) {
		printf("Unbale to connect to server!\n");
		WSACleanup();
		return 1;
	}
	//发送缓冲区中的测试数据
	iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
	if(iResult == SOCKET_ERROR) {
		printf("send failed with error: %d\n", WSAGetLastError());
		closesocket(ConnectSocket);
		WSACleanup();
		return 1;
	}
	printf("Bytes Sent: %ld\n", iResult);
	//数据发送结束,调用shutdown()函数声明不再发送数据,此时客户端仍可以接收数据
	iResult = shutdown(ConnectSocket, SD_SEND);
	if(iResult == SOCKET_ERROR) {
		printf("shutdown failed with error: %d\n", WSAGetLastError());
		closesocket(ConnectSocket);
		WSACleanup();
		return 1;
	}
	//持续接收数据,直到服务器关闭连接
	do {
		iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
		if(iResult > 0) 
			printf("Bytes received: %d\n", iResult);
		else if(iResult == 0) 
			printf("Connection closed\n");
		else 
			printf("recv failed with error: %d\n", WSAGetLastError());
	}while(iResult > 0);
	//关闭套接字
	closesocket(ConnectSocket);
	//释放资源
	WSACleanup();
	return 0;
}

你可能感兴趣的:(服务器,网络,Windows)