客户端
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main() {
// 创建客户端套接字
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket == -1) {
std::cerr << "Error creating socket\n";
return -1;
}
// 服务器地址结构
sockaddr_in serverAddr;
std::memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8080); // 服务器监听端口
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 服务器IP地址
// 连接到服务器
if (connect(clientSocket, reinterpret_cast<struct sockaddr*>(&serverAddr), sizeof(serverAddr)) == -1) {
std::cerr << "Error connecting to server\n";
close(clientSocket);
return -1;
}
std::cout << "Connected to server\n";
// 循环发送数据
while (true) {
std::string message;
std::cout << "Enter message to send (or 'exit' to quit): ";
std::getline(std::cin, message);
if (message == "exit") {
break;
}
if (send(clientSocket, message.c_str(), message.size(), 0) == -1) {
std::cerr << "Error sending data\n";
break;
}
}
// 关闭客户端套接字
close(clientSocket);
return 0;
}
服务器
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main() {
// 创建服务器套接字
int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == -1) {
std::cerr << "Error creating socket\n";
return -1;
}
// 服务器地址结构
sockaddr_in serverAddr;
std::memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(23); // 服务器监听端口
serverAddr.sin_addr.s_addr = inet_addr("192.168.0.7");
// 绑定服务器地址
if (bind(serverSocket, reinterpret_cast<struct sockaddr*>(&serverAddr), sizeof(serverAddr)) == -1) {
std::cerr << "Error binding socket\n";
close(serverSocket);
return -1;
}
// 监听连接请求
if (listen(serverSocket, 5) == -1) {
std::cerr << "Error listening on socket\n";
close(serverSocket);
return -1;
}
std::cout << "Server listening on port 23...\n";
while (true) {
// 接受连接
sockaddr_in clientAddr;
socklen_t clientAddrLen = sizeof(clientAddr);
int clientSocket = accept(serverSocket, reinterpret_cast<struct sockaddr*>(&clientAddr), &clientAddrLen);
if (clientSocket == -1) {
std::cerr << "Error accepting connection\n";
continue;
}
std::cout << "Client connected\n";
// 循环接收数据
char buffer[1024 * 1024 * 1];
int bytesRead;
while ((bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0)) > 0) {
buffer[bytesRead] = '\0';
std::cout << "Received data from client: " << buffer << std::endl;
}
if (bytesRead == 0) {
std::cout << "Client disconnected\n";
} else {
std::cerr << "Error receiving data\n";
}
// 关闭客户端套接字
close(clientSocket);
}
// 关闭服务器套接字
close(serverSocket);
return 0;
}