C++实现socket通讯的代码
时间: 2023-07-26 14:04:40 浏览: 71
C++ 实现简单socket 客户端+服务器源码
以下是使用C++实现Socket通讯的示例代码:
客户端:
```
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PORT 8080
int main(int argc, char const *argv[]) {
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *hello = "Hello, Server!";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
std::cout << "Socket creation error" << std::endl;
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
std::cout << "Invalid address/ Address not supported" << std::endl;
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
std::cout << "Connection Failed" << std::endl;
return -1;
}
send(sock, hello, strlen(hello), 0);
std::cout << "Hello message sent" << std::endl;
valread = read(sock, buffer, 1024);
std::cout << buffer << std::endl;
return 0;
}
```
在上面的代码中,首先创建了一个Socket,然后设置连接服务器的信息。接着连接到服务器,并发送一段数据。然后接收服务器返回的数据,并输出到控制台。需要注意的是,客户端需要知道服务器的IP地址和端口号。
服务器端:
```
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PORT 8080
int main(int argc, char const *argv[]) {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello, Client!";
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
std::cout << "Socket creation error" << std::endl;
return -1;
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
std::cout << "Setsockopt error" << std::endl;
return -1;
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
std::cout << "Bind error" << std::endl;
return -1;
}
if (listen(server_fd, 3) < 0) {
std::cout << "Listen error" << std::endl;
return -1;
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
std::cout << "Accept error" << std::endl;
return -1;
}
valread = read(new_socket, buffer, 1024);
std::cout << buffer << std::endl;
send(new_socket, hello, strlen(hello), 0);
std::cout << "Hello message sent" << std::endl;
return 0;
}
```
在上面的代码中,首先创建了一个Socket,并设置Socket选项。然后绑定到一个本地地址和端口号,开始监听连接请求。当有客户端连接上来后,接收客户端发送的数据,并发送一段数据。需要注意的是,服务器端需要绑定到一个固定的IP地址和端口号,并在等待客户端的连接请求。
阅读全文