如何用C++实现socket通讯
时间: 2023-08-30 16:06:16 浏览: 162
在C++中实现socket通讯需要使用操作系统提供的socket API。下面是一个简单的例子,展示了如何创建一个TCP服务器和一个TCP客户端进行通讯。
服务器端代码:
```cpp
#include <iostream>
#include <winsock2.h>
using namespace std;
int main()
{
// 初始化Winsock库
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
cout << "WSAStartup failed: " << result << endl;
return 1;
}
// 创建socket
SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET) {
cout << "socket failed: " << WSAGetLastError() << endl;
WSACleanup();
return 1;
}
// 绑定socket到本地IP和端口
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(12345);
addr.sin_addr.s_addr = INADDR_ANY;
result = bind(listenSocket, (sockaddr*)&addr, sizeof(addr));
if (result == SOCKET_ERROR) {
cout << "bind failed: " << WSAGetLastError() << endl;
closesocket(listenSocket);
WSACleanup();
return 1;
}
// 监听socket
result = listen(listenSocket, SOMAXCONN);
if (result == SOCKET_ERROR) {
cout << "listen failed: " << WSAGetLastError() << endl;
closesocket(listenSocket);
WSACleanup();
return 1;
}
// 接受客户端连接
sockaddr_in clientAddr;
int clientAddrSize = sizeof(clientAddr);
SOCKET clientSocket = accept(listenSocket, (sockaddr*)&clientAddr, &clientAddrSize);
if (clientSocket == INVALID_SOCKET) {
cout << "accept failed: " << WSAGetLastError() << endl;
closesocket(listenSocket);
WSACleanup();
return 1;
}
// 从客户端接收数据
char buffer[1024];
result = recv(clientSocket, buffer, sizeof(buffer), 0);
if (result == SOCKET_ERROR) {
cout << "recv failed: " << WSAGetLastError() << endl;
closesocket(clientSocket);
closesocket(listenSocket);
WSACleanup();
return 1;
}
// 处理客户端发送的数据
cout << "Received from client: " << buffer << endl;
// 关闭socket
closesocket(clientSocket);
closesocket(listenSocket);
WSACleanup();
return 0;
}
```
客户端代码:
```cpp
#include <iostream>
#include <winsock2.h>
using namespace std;
int main()
{
// 初始化Winsock库
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
cout << "WSAStartup failed: " << result << endl;
return 1;
}
// 创建socket
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
cout << "socket failed: " << WSAGetLastError() << endl;
WSACleanup();
return 1;
}
// 连接服务器
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(12345);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
result = connect(clientSocket, (sockaddr*)&serverAddr, sizeof(serverAddr));
if (result == SOCKET_ERROR) {
cout << "connect failed: " << WSAGetLastError() << endl;
closesocket(clientSocket);
WSACleanup();
return 1;
}
// 发送数据到服务器
const char* message = "Hello, server!";
result = send(clientSocket, message, strlen(message), 0);
if (result == SOCKET_ERROR) {
cout << "send failed: " << WSAGetLastError() << endl;
closesocket(clientSocket);
WSACleanup();
return 1;
}
// 关闭socket
closesocket(clientSocket);
WSACleanup();
return 0;
}
```
在Windows环境下编译运行上述代码,即可实现简单的socket通讯。
阅读全文