使用C++实现socket连接
时间: 2024-01-31 21:04:35 浏览: 184
vc++实现socket
4星 · 用户满意度95%
下面是一个简单的使用C++实现socket连接的示例代码,其中实现了客户端和服务器端之间的基本通信。
服务器端代码:
```c++
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
using namespace std;
int main() {
// 创建socket
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
cerr << "创建socket失败" << endl;
return -1;
}
cout << "socket创建成功" << endl;
// 绑定IP地址和端口号
struct sockaddr_in server_addr{};
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(12345);
if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1) {
cerr << "绑定IP地址和端口号失败" << endl;
close(server_socket);
return -1;
}
cout << "绑定IP地址和端口号成功" << endl;
// 监听连接请求
if (listen(server_socket, 10) == -1) {
cerr << "监听连接请求失败" << endl;
close(server_socket);
return -1;
}
cout << "等待客户端连接..." << endl;
// 接受连接请求
struct sockaddr_in client_addr{};
socklen_t client_addr_len = sizeof(client_addr);
int client_socket = accept(server_socket, (struct sockaddr *) &client_addr, &client_addr_len);
if (client_socket == -1) {
cerr << "接受连接请求失败" << endl;
close(server_socket);
return -1;
}
cout << "客户端连接成功" << endl;
// 接收客户端发送的数据
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
if (recv(client_socket, buffer, sizeof(buffer), 0) == -1) {
cerr << "接收数据失败" << endl;
close(client_socket);
close(server_socket);
return -1;
}
cout << "接收到客户端发送的数据:" << buffer << endl;
// 发送数据给客户端
const char *msg = "Hello, I'm server.";
if (send(client_socket, msg, strlen(msg), 0) == -1) {
cerr << "发送数据失败" << endl;
close(client_socket);
close(server_socket);
return -1;
}
cout << "发送数据成功" << endl;
// 关闭socket
close(client_socket);
close(server_socket);
return 0;
}
```
客户端代码:
```c++
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
using namespace std;
int main() {
// 创建socket
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket == -1) {
cerr << "创建socket失败" << endl;
return -1;
}
cout << "socket创建成功" << endl;
// 连接服务器
struct sockaddr_in server_addr{};
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(12345);
if (connect(client_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1) {
cerr << "连接服务器失败" << endl;
close(client_socket);
return -1;
}
cout << "连接服务器成功" << endl;
// 发送数据给服务器
const char *msg = "Hello, I'm client.";
if (send(client_socket, msg, strlen(msg), 0) == -1) {
cerr << "发送数据失败" << endl;
close(client_socket);
return -1;
}
cout << "发送数据成功" << endl;
// 接收服务器发送的数据
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
if (recv(client_socket, buffer, sizeof(buffer), 0) == -1) {
cerr << "接收数据失败" << endl;
close(client_socket);
return -1;
}
cout << "接收到服务器发送的数据:" << buffer << endl;
// 关闭socket
close(client_socket);
return 0;
}
```
以上代码仅供参考,具体实现需要根据具体场景进行调整。
阅读全文