c++中socket通信例子
时间: 2024-10-01 18:06:45 浏览: 30
QT中使用C++ socket通信 客户端与服务端的代码实例
5星 · 资源好评率100%
在C++中,Socket通信通常用于网络应用程序,比如客户端服务器模型。下面是一个简单的TCP套接字通信的例子,展示了一个基础的服务器如何接收客户端的消息:
```cpp
#include <iostream>
#include <sys/socket.h> // For socket functions
#include <netinet/in.h> // For Internet address structures
#include <arpa/inet.h> // For inet_pton function
#include <unistd.h> // For read and write
// Server code
int main() {
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
std::cerr << "Failed to create socket" << std::endl;
return 1;
}
sockaddr_in server_addr;
server_addr.sin_family = AF_INET; // IPv4
server_addr.sin_port = htons(8000); // Port number, in network byte order
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
bind(server_socket, (sockaddr*)&server_addr, sizeof(server_addr));
listen(server_socket, 5); // Maximum of 5 pending connections
sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int client_socket = accept(server_socket, (sockaddr*)&client_addr, &client_len);
char buffer[1024];
while (true) { // Infinite loop for receiving messages
size_t bytes_received = recv(client_socket, buffer, sizeof(buffer), 0);
if (bytes_received > 0) {
std::cout << "Client says: " << buffer << std::endl;
send(client_socket, "Echo received", strlen("Echo received"), 0); // Send reply
} else if (bytes_received == 0) {
std::cout << "Client disconnected" << std::endl;
break;
} else {
perror("Error reading from client");
break;
}
}
close(client_socket);
close(server_socket);
return 0;
}
// Client code (not shown here, but similar)
int main() {
// Create a socket, connect to the server, and send/receive data
// ...
return 0;
}
```
在这个例子中,服务器创建一个监听套接字,等待客户端连接。当有客户端连接并发送数据时,服务器接收数据,打印出来,并回送一个简单的确认消息。
注意这只是一个基本示例,实际应用中需要处理更多的细节,如错误检查、线程安全以及网络连接关闭等。
阅读全文