当然,下面是一个简单的基于TCP协议的Linux socket客户端代码示例:
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
int main() {
int clientSocket;
sockaddr_in serverAddress{};
char buffer[1024];
// 创建客户端套接字
clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket == -1) {
std::cerr << "Failed to create socket" << std::endl;
return 1;
}
// 设置服务器地址和端口
serverAddress.sin_family = AF_INET; // IPv4协议
serverAddress.sin_port = htons(8080); // 使用8080端口
if (inet_pton(AF_INET, "127.0.0.1", &(serverAddress.sin_addr)) <= 0) {
std::cerr << "Invalid address/ Address not supported" << std::endl;
close(clientSocket);
return 1;
}
// 连接服务器
if (connect(clientSocket, reinterpret_cast<sockaddr*>(&serverAddress), sizeof(serverAddress)) == -1) {
std::cerr << "Failed to connect to server" << std::endl;
close(clientSocket);
return 1;
}
// 发送数据到服务器
const char* message = "Hello from client!";
ssize_t bytesSent = send(clientSocket, message, strlen(message), 0);
if (bytesSent == -1) {
std::cerr << "Failed to send data to server" << std::endl;
close(clientSocket);
return 1;
}
// 接收服务器的回复
memset(buffer, 0, sizeof(buffer));
ssize_t bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0);
if (bytesRead == -1) {
std::cerr << "Failed to receive data from server" << std::endl;
close(clientSocket);
return 1;
}
std::cout << "Received message from server: " << buffer << std::endl;
// 关闭套接字
close(clientSocket);
return 0;
}
该示例创建了一个简单的TCP客户端,连接到本地8080端口,并向服务器发送一条消息并接收其回复。你可以根据自己的需求进行修改和扩展。
内容由零声教学AI助手提供,问题来源于学员提问