1
TimeNewRome OP 以下是 client 端代码:
void send(const std::string& message) { int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) { std::cerr << "Could not create socket" << std::endl; return; } int sendBufferSize = 65536; if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sendBufferSize, sizeof(sendBufferSize)) < 0) { std::cerr << "Could not set send buffer size" << std::endl; close(sock); return; } sockaddr_in server; server.sin_addr.s_addr = inet_addr("10.130.9.6"); server.sin_family = AF_INET; server.sin_port = htons(8091); if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) { std::cerr << "Connect failed. Error" << std::endl; close(sock); return; } if (send(sock, message.c_str(), message.length(), 0) < 0) { std::cerr << "Send failed" << std::endl; } close(sock); } |
2
TimeNewRome OP 以下是 server 端代码:
int main() { int server_fd, new_socket; struct sockaddr_in address; int addrlen = sizeof(address); char buffer[32768] = {0}; if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(8091); if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { perror("bind failed"); close(server_fd); exit(EXIT_FAILURE); } if (listen(server_fd, 3) < 0) { perror("listen"); close(server_fd); exit(EXIT_FAILURE); } while (true) { if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) { perror("accept"); close(server_fd); exit(EXIT_FAILURE); } int valread = read(new_socket, buffer, 1024); if (valread > 0) { std::cout << buffer << std::endl; memset(buffer, 0, sizeof(buffer)); } close(new_socket); } close(server_fd); return 0; } |
3
TimeNewRome OP 使用 perror 函数的输出结果是“Connect failed: Cannot assign requested address.”
|