詳談C++ socket網絡編程實例(2)

功能

完成Cpp客戶端簡單功能,可收發數據。

Cpp服務端實例地址:【點擊跳轉】

源碼

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
//網絡庫文件
#include <winsock2.h>
//引入ws2_32.lib
#pragma comment(lib,"ws2_32.lib")
using std::cout;
using std::endl;
using std::cin;
int main()
{
	system("chcp 65001");
	WSADATA wsaData;
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
	{
		cout << "WSAStartUp error " << GetLastError() << endl;
		return 0;
	}
	//1、創建句柄
	SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, 0);
	//2、連接服務端
	// connect(綁定的句柄, 服務端地址, 第二個參數的大小);
	SOCKADDR_IN ServerAddr;
	ServerAddr.sin_family = AF_INET;
	ServerAddr.sin_port = htons(7890);
	ServerAddr.sin_addr.s_addr = inet_addr("127.0.0.1");//點分十進制轉化為十進制
	if (SOCKET_ERROR == connect(clientSocket, (sockaddr *)&ServerAddr, sizeof(SOCKADDR_IN)))
	{
		cout << "連接失敗" << endl;
		return 0;
	}
	//3、接收發送數據
	while (true)
	{
		char buffer[1024] = { 0 };
		scanf("%s", buffer);
		send(clientSocket, buffer, strlen(buffer), 0);
		int nRecv = recv(clientSocket, buffer, 1024, 0);
		if (nRecv <= 0)
		{
			break;
		}
		printf("[%d]接收數據, %s\n", nRecv, buffer);
	}
	printf("斷開連接\n");
	//4、關閉句柄
	return 0;
}

效果

效果圖

總結

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

推薦閱讀: