c++ socket通信代码示例
时间: 2024-04-19 12:20:22 浏览: 108
Socket通讯代码示例
4星 · 用户满意度95%
当然,我可以给你提供一个简单的C++ Socket通信代码示例。以下是一个基于TCP协议的客户端和服务器端的示例代码:
服务器端代码:
```cpp
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
// 创建socket
int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == -1) {
std::cerr << "Failed to create socket." << std::endl;
return -1;
}
// 准备地址信息
sockaddr_in serverAddress{};
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = INADDR_ANY;
serverAddress.sin_port = htons(8888);
// 绑定socket到指定地址和端口
if (bind(serverSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) {
std::cerr << "Failed to bind socket." << std::endl;
return -1;
}
// 监听连接请求
if (listen(serverSocket, 3) < 0) {
std::cerr << "Failed to listen." << std::endl;
return -1;
}
std::cout << "Waiting for incoming connections..." << std::endl;
// 接受连接请求
int clientSocket;
sockaddr_in clientAddress{};
socklen_t clientAddressLength = sizeof(clientAddress);
clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddress, &clientAddressLength);
if (clientSocket < 0) {
std::cerr << "Failed to accept connection." << std::endl;
return -1;
}
std::cout << "Client connected." << std::endl;
// 接收和发送数据
char buffer[1024] = {0};
std::string message = "Hello from server!";
send(clientSocket, message.c_str(), message.length(), 0);
std::cout << "Message sent to client: " << message << std::endl;
int bytesRead = read(clientSocket, buffer, 1024);
if (bytesRead > 0) {
std::cout << "Message received from client: " << buffer << std::endl;
}
// 关闭socket
close(clientSocket);
close(serverSocket);
return 0;
}
```
客户端代码:
```cpp
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
// 创建socket
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket == -1) {
std::cerr << "Failed to create socket." << std::endl;
return -1;
}
// 准备服务器地址信息
sockaddr_in serverAddress{};
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(8888);
// 将IP地址从字符串转换为网络字节序
if (inet_pton(AF_INET, "127.0.0.1", &(serverAddress.sin_addr)) <= 0) {
std::cerr << "Invalid address/ Address not supported." << std::endl;
return -1;
}
// 连接到服务器
if (connect(clientSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) {
std::cerr << "Connection failed." << std::endl;
return -1;
}
// 接收和发送数据
char buffer[1024] = {0};
int bytesRead = read(clientSocket, buffer, 1024);
if (bytesRead > 0) {
std::cout << "Message received from server: " << buffer << std::endl;
}
std::string message = "Hello from client!";
send(clientSocket, message.c_str(), message.length(), 0);
std::cout << "Message sent to server: " << message << std::endl;
// 关闭socket
close(clientSocket);
return 0;
}
```
这个示例展示了一个简单的客户端和服务器端的通信过程。服务器端首先创建一个socket,然后绑定到指定的地址和端口,并开始监听连接请求。当有客户端连接时,服务器端接受连接请求,并发送一条消息给客户端。客户端连接到服务器,并接收服务器发送的消息后,发送一条消息给服务器。最后,两端关闭socket。
阅读全文