詳談C++ socket網絡編程實例

功能

實現基於sokcet的Cpp服務端

TIPS:功能包括接收客戶端的數據,向客戶端發送數據。

源碼

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <iostream>
//#include <windows.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32")
using std::cout;
using std::endl;
using std::cin;

int main()
{
	system("chcp 65001");
	//SetConsoleOutputCP(65001);
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);//啟動window動態網絡庫
	//1.創建socket
	//SOCKET == 句柄 == 文件描述符 == 套接字
	//socket(協議族類型,協議類型,0);
	//協議族類型 IPV4(AF_INET) IPV6
	//協議類型 TCP(SOCK_STREAM),UDP(SOCK_DROP)
	SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);//IPPROTO_TCP
	if (serverSocket == INVALID_SOCKET)
	{
		cout << "創建socket失敗" << endl;
		return 0;
	}
	//2.綁定ip和端口號
	//127.0.0.1 永遠指向本機
	//0.0.0.o 綁定所有網卡的ip
	SOCKADDR_IN serverAddr;
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(7890);//host to networks short,將主機字節序轉化為網絡字節序
	serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");//點分十進制轉換為10進制
	if (SOCKET_ERROR == bind(serverSocket, (sockaddr *)&serverAddr, sizeof(SOCKADDR_IN)))
	{
		cout << "bind 失敗" << endl;
		return 0;
	}
	cout << "bind 成功" << endl;
	//3.監聽,提示本機的操作系統
	if (INVALID_SOCKET == listen(serverSocket, 5))
	{
		cout << "listen 失敗" << endl;
		return 0;
	}
	cout << "listen 成功" << endl;
	while(true)
	{
		//4.等待客戶端連接
		SOCKADDR_IN clientAddr;
		int addrLen = sizeof(SOCKADDR_IN);
		SOCKET clientSocket = accept(serverSocket, (SOCKADDR *)&clientAddr, &addrLen);
		if (INVALID_SOCKET == clientSocket)
		{
			cout << "客戶端連接失敗 " << endl;
			return 0;
		}
		cout << "client ok " << inet_ntoa(clientAddr.sin_addr) << endl;
		cout << "port " << ntohs(clientAddr.sin_port) << endl;
		//5.收發數據
		//接收數據
		char recvBuffer[1024]{ 0 };
		int nRecv = recv(clientSocket, recvBuffer, 1024, 0);
		cout << "recvLen:" << nRecv << "內容:" << recvBuffer << endl;
		//發送數據
		int nSend = send(clientSocket, recvBuffer, nRecv, 0);
		cout << "send Len:" << nSend << endl;
		//6.關閉客戶端
		closesocket(clientSocket);
	}
	//7.關閉服務端
	closesocket(serverSocket);

	WSACleanup();//卸載window動態網絡庫
	return 0;
}

效果

TIPS:利用sokit模擬工具模擬一個客戶端終端。

效果圖

總結

本篇文章就到這裡瞭,希望能夠給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!

推薦閱讀: