Windows10 VS2017 C++ Server Socket簡單伺服器端與客戶端

大囚長發表於2018-12-24

服務端:

#include "pch.h"
#include<iostream>
#include<WinSock2.h>
#include <Ws2tcpip.h>

#define CONNECT_NUM_MAX 10

#pragma comment(lib, "ws2_32.lib")


using namespace std;


int main()
{
	//載入套接字型檔
	WSADATA wsaData;
	int iRet = 0;
	iRet = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iRet != 0)
	{
		cout << "WSAStartup(MAKEWORD(2, 2), &wsaData) execute failed!" << endl;;
		return -1;
	}
	if (2 != LOBYTE(wsaData.wVersion) || 2 != HIBYTE(wsaData.wVersion))
	{
		WSACleanup();
		cout << "WSADATA version is not correct!" << endl;
		return -1;
	}

	//建立套接字
	SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
	if (serverSocket == INVALID_SOCKET)
	{
		cout << "serverSocket = socket(AF_INET, SOCK_STREAM, 0) execute failed!" << endl;
		return -1;
	}

	//初始化伺服器地址族變數
	SOCKADDR_IN addrSrv;
	addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_port = htons(6000);

	//繫結
	iRet = bind(serverSocket, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
	if (iRet == SOCKET_ERROR)
	{
		cout << "bind(serverSocket, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)) execute failed!" << endl;
		return -1;
	}


	//監聽
	iRet = listen(serverSocket, CONNECT_NUM_MAX);
	if (iRet == SOCKET_ERROR)
	{
		cout << "listen(serverSocket, 10) execute failed!" << endl;
		return -1;
	}
	else
	{
		cout << "Server is listening on " << addrSrv.sin_addr.S_un.S_addr << ":" << addrSrv.sin_port << "." << endl;
	}

	//等待連線_接收_傳送
	SOCKADDR_IN clientAddr;
	int len = sizeof(SOCKADDR);
	while (1)
	{
		SOCKET connSocket = accept(serverSocket, (SOCKADDR*)&clientAddr, &len);
		if (connSocket == INVALID_SOCKET)
		{
			cout << "accept(serverSocket, (SOCKADDR*)&clientAddr, &len) execute failed!" << endl;
			return -1;
		}
		else
		{
			cout << "Connection established! Waiting for messages." << endl;
		}

		int x = 0;

		while (true)
		{
			//接收訊息
			char recvBuf[100];
			int sig = recv(connSocket, recvBuf, 100, 0);
			//沒有連線時斷開
			if (sig <= 0)
			{
				printf("Error: Lost connection!\n");
				break;
			}
			printf("%s\n", recvBuf);

			//傳送訊息
			char sendBuf[100];
			//sprintf_s(sendBuf, "Welcome %s", inet_ntoa(clientAddr.sin_addr));
			char str[INET_ADDRSTRLEN];
			sprintf_s(sendBuf, "Welcome! client from %s %d!", inet_ntop(AF_INET, &clientAddr.sin_addr, str, sizeof(str)), x);
			send(connSocket, sendBuf, strlen(sendBuf) + 1, 0);
			x++;
		}

		//關閉連線
		closesocket(connSocket);
	}

	system("pause");
	return 0;
}

多執行緒服務端:
server.h

#ifndef SERVER_H
#define SERVER_H

#include <Winsock2.h>
#include <windows.h>

#pragma comment (lib, "ws2_32.lib")

#define IP_BUF_SIZE 129

class Server
{
public:
	Server();
	~Server();
	Server(const Server &) = delete;
	Server & operator=(const Server &) = delete;
	void WaitForClient();
private:
	WORD winsock_ver;
	WSADATA wsa_data;
	SOCKET sock_svr;
	SOCKET sock_clt;
	HANDLE h_thread;
	SOCKADDR_IN addr_svr;
	SOCKADDR_IN addr_clt;
	int ret_val;
	int addr_len;
	PWSTR buf_ip[IP_BUF_SIZE];
};

#endif

#include <iostream>
#include <WS2tcpip.h>

using std::cerr;
using std::cout;
using std::endl;

#define SERVER_PORT 6000
#define MSG_BUF_SIZE 1024

Server::Server()
{
	cout << "Initializing server...\n";
	//
	winsock_ver = MAKEWORD(2, 2);
	addr_len = sizeof(SOCKADDR_IN);
	addr_svr.sin_family = AF_INET;
	addr_svr.sin_port = ::htons(SERVER_PORT);
	addr_svr.sin_addr.S_un.S_addr = ADDR_ANY;
	memset(buf_ip, 0, IP_BUF_SIZE);
	//
	ret_val = ::WSAStartup(winsock_ver, &wsa_data);
	if (ret_val != 0)
	{
		cerr << "WSA failed to start up!Error code: " << ::WSAGetLastError() << "\n";
		system("pause");
		exit(1);
	}
	cout << "WSA started up successfully...\n";
	//
	sock_svr = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (sock_svr == INVALID_SOCKET)
	{
		cerr << "Failed to create server socket!Error code: " << ::WSAGetLastError() << "\n";
		::WSACleanup();
		system("pause");
		exit(1);
	}
	cout << "Server socket created successfully...\n";
	//
	ret_val = ::bind(sock_svr, (SOCKADDR*)&addr_svr, addr_len);
	if (ret_val != 0)
	{
		cerr << "Failed to bind server socket!Error code: " << ::WSAGetLastError() << "\n";
		::WSACleanup();
		system("pause");
		exit(1);
	}
	cout << "Server socket bound successfully...\n";
	//
	ret_val = ::listen(sock_svr, SOMAXCONN);
	if (ret_val == SOCKET_ERROR)
	{
		cerr << "Server socket failed to listen!Error code: " << ::WSAGetLastError() << "\n";
		::WSACleanup();
		system("pause");
		exit(1);
	}
	cout << "Server socket started to listen...\n";
	//
	cout << "Server started successfully..." << endl;
}

Server::~Server()
{
	::closesocket(sock_svr);
	::closesocket(sock_clt);
	::WSACleanup();
	cout << "Socket closed..." << endl;
}

DWORD WINAPI CreateClientThread(LPVOID lpParameter);
//
void Server::WaitForClient()
{
	while (true)
	{
		sock_clt = ::accept(sock_svr, (SOCKADDR*)&addr_clt, &addr_len);
		if (sock_clt == INVALID_SOCKET)
		{
			cerr << "Failed to accept client!Error code: " << ::WSAGetLastError() << "\n";
			::WSACleanup();
			system("pause");
			exit(1);
		}
		::InetNtop(addr_clt.sin_family, &addr_clt, *buf_ip, IP_BUF_SIZE);
		cout << "A new client connected...IP address: " << buf_ip << ", port number: " << ::ntohs(addr_clt.sin_port) << endl;
		h_thread = ::CreateThread(nullptr, 0, CreateClientThread, (LPVOID)sock_clt, 0, nullptr);
		if (h_thread == NULL)
		{
			cerr << "Failed to create a new thread!Error code: " << ::WSAGetLastError() << "\n";
			::WSACleanup();
			system("pause");
			exit(1);
		}
		::CloseHandle(h_thread);
	}
}

DWORD WINAPI CreateClientThread(LPVOID lpParameter)
{
	SOCKET sock_clt = (SOCKET)lpParameter;
	char buf_msg[MSG_BUF_SIZE];
	int ret_val = 0;
	int snd_result = 0;
	do
	{
		memset(buf_msg, 0, MSG_BUF_SIZE);
		ret_val = ::recv(sock_clt, buf_msg, MSG_BUF_SIZE, 0);
		if (ret_val > 0)
		{
			if (strcmp(buf_msg, "exit") == 0)
			{
				cout << "Client requests to close the connection..." << endl;
				break;
			}
			cout << "Message received: " << buf_msg << endl;
			snd_result = ::send(sock_clt, buf_msg, MSG_BUF_SIZE, 0);
			if (snd_result == SOCKET_ERROR)
			{
				cerr << "Failed to send message to client!Error code: " << ::GetLastError() << "\n";
				::closesocket(sock_clt);
				system("pause");
				return 1;
			}
		}
		else if (ret_val == 0)
		{
			cout << "connection closed..." << endl;
		}
		else
		{
			cerr << "Failed to receive message from client!Error code: " << ::GetLastError() << "\n";
			::closesocket(sock_clt);
			system("pause");
			return 1;
		}
	} while (ret_val > 0);
	//
	ret_val = ::shutdown(sock_clt, SD_SEND);
	if (ret_val == SOCKET_ERROR)
	{
		cerr << "Failed to shutdown the client socket!Error code: " << ::GetLastError() << "\n";
		::closesocket(sock_clt);
		system("pause");
		return 1;
	}
	return 0;
}

server.cpp

#include "pch.h"
#include "server.h"

int main()
{
	Server svr;
	svr.WaitForClient();
	system("pause");
	return 0;
}

客戶端:

#include "pch.h"
#include<iostream>
#include <winsock2.h>
#include <Ws2tcpip.h>


using namespace std;

#pragma comment(lib, "ws2_32.lib")


int main()
{
	//載入套接字型檔
	WSADATA wsaData;
	int iRet = 0;
	iRet = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iRet != 0)
	{
		cout << "WSAStartup(MAKEWORD(2, 2), &wsaData) execute failed!" << endl;
		return -1;
	}
	if (2 != LOBYTE(wsaData.wVersion) || 2 != HIBYTE(wsaData.wVersion))
	{
		WSACleanup();
		cout << "WSADATA version is not correct!" << endl;
		return -1;
	}

	//建立套接字
	SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, 0);
	if (clientSocket == INVALID_SOCKET)
	{
		cout << "clientSocket = socket(AF_INET, SOCK_STREAM, 0) execute failed!" << endl;
		return -1;
	}

	//初始化伺服器端地址族變數
	SOCKADDR_IN srvAddr;
	//srvAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	inet_pton(AF_INET, "127.0.0.1", &srvAddr.sin_addr);
	srvAddr.sin_family = AF_INET;
	srvAddr.sin_port = htons(6000);

	//連線伺服器
	iRet = connect(clientSocket, (SOCKADDR*)&srvAddr, sizeof(SOCKADDR));
	if (0 != iRet)
	{
		cout << "connect(clientSocket, (SOCKADDR*)&srvAddr, sizeof(SOCKADDR)) execute failed!" << endl;
		return -1;
	}

	int x = 0;
	
	while (true)
	{
		x++;

		//傳送訊息
		char sendBuf[100];
		sprintf_s(sendBuf, "Hello, this is client %s %d!", "bunny", x);
		printf(sendBuf);
		printf("\n");
		send(clientSocket, sendBuf, strlen(sendBuf) + 1, 0);

		//接收訊息
		char recvBuf[100];
		int sig = recv(clientSocket, recvBuf, 100, 0);
		//沒有連線時斷開
		if (sig <=0)
		{
			printf("Error: Lost connection!\n");
			break;
		}
		printf("%s\n", recvBuf);

		//跳出
		if (x==20)
		{
			break;
		}

		Sleep(3000);
	}

	//清理
	closesocket(clientSocket);
	WSACleanup();

	system("pause");
	return 0;
}

參考地址:
https://www.cnblogs.com/darren45/p/4818867.html
https://blog.csdn.net/zyy617532750/article/details/58595700/
https://www.cnblogs.com/jzincnblogs/p/5189636.html
https://blog.csdn.net/s_lisheng/article/details/74502795

相關文章