您的当前位置:首页正文

【在Linux世界中追寻伟大的One Piece】验证TCP

2024-11-11 来源:个人技术集锦

1 -> 验证TCP-windows作为client访问Linux

1.1 -> TCP client样例代码


1 -> 验证TCP-windows作为client访问Linux

1.1 -> TCP client样例代码

#include <winsock2.h>
#include <iostream>
#include <string>

#pragma warning(disable : 4996)
#pragma comment(lib, "ws2_32.lib")

std::string serverip = ""; // 填写你的云服务器 ip
uint16_t serverport = 8888; // 填写你的云服务开放的端口号

int main()
{
	WSADATA wsaData;
	int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (result != 0)
	{
		std::cerr << "WSAStartup failed: " << result << std::endl;

		return 1;
	}

	SOCKET clientSocket = socket(AF_INET, SOCK_STREAM,
		IPPROTO_TCP);
	if (clientSocket == INVALID_SOCKET)
	{
		std::cerr << "socket failed" << std::endl;

		WSACleanup();

		return 1;
	}

	sockaddr_in serverAddr;

	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(serverport);
	serverAddr.sin_addr.s_addr = inet_addr(serverip.c_str());

	result = connect(clientSocket, (SOCKADDR*)&serverAddr,
		sizeof(serverAddr));
	if (result == SOCKET_ERROR)
	{
		std::cerr << "connect failed" << std::endl;

		closesocket(clientSocket);

		WSACleanup();

		return 1;
	}

	while (true)
	{
		std::string message;
		std::cout << "Please Enter@ ";
		std::getline(std::cin, message);
		if (message.empty()) 
			continue;

		send(clientSocket, message.c_str(), message.size(), 0);
		char buffer[1024] = { 0 };
		int bytesReceived = recv(clientSocket, buffer,
			sizeof(buffer) - 1, 0);
		if (bytesReceived > 0)
		{
			buffer[bytesReceived] = '\0'; // 确保字符串以 null 结尾
			std::cout << "Received from server: " << buffer <<
				std::endl;
		}
		else
		{
			std::cerr << "recv failed" << std::endl;
		}
	}

	closesocket(clientSocket);

	WSACleanup();

	return 0;
}

关闭client,服务器端也看到了退出的消息。

WSAStartup函数是Windows Sockets API的初始化函数,它用于初始化Winsock库。该函数在应用程序或DLL调用任何Windows套接字函数之前必须首先执行,它扮演着初始化的角色。


以下是WSAStartup函数的一些关键点:
它接受两个参数:wVersionRequested和lpWSAData

  • wVersionRequested用于指定所请求的Winsock版本,通常使用MAKEWORD(major, minor)宏,其中major和minor分别表示请求的主版本号和次版本号。
  • lpWSAData是一个指向WSADATA结构的指针,用于接收初始化信息。如果函数调用成功,它会返回 0;否则,返回错误代码。

感谢各位大佬支持!!!

互三啦!!!

Top