C++ socket套接字编程示例代码
时间: 2024-09-14 16:07:00 浏览: 61
C++中的socket套接字编程是一种让程序能够进行网络通信的方式。以下是使用C++进行TCP套接字编程的一个简单示例,分别展示了服务器端和客户端的代码。
服务器端示例代码:
```cpp
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
const char *greeting = "Hello from server";
// 创建socket文件描述符
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 绑定socket到地址和端口
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8080);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听socket
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
// 接受来自客户端的连接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// 读取客户端发送的数据
read(new_socket, buffer, 1024);
std::cout << "Message from client: " << buffer << std::endl;
// 向客户端发送数据
send(new_socket, greeting, strlen(greeting), 0);
std::cout << "Greeting message sent\n";
// 关闭socket
close(server_fd);
return 0;
}
```
客户端示例代码:
```cpp
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
const char *hello = "Hello from client";
char buffer[1024] = {0};
// 创建socket文件描述符
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
std::cout << "\n Socket creation error \n";
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8080);
// 将IPv4和IPv6地址从文本转换为二进制形式
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
std::cout << "\nInvalid address/ Address not supported \n";
return -1;
}
// 连接到服务器
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
std::cout << "\nConnection Failed \n";
return -1;
}
// 发送数据到服务器
send(sock, hello, strlen(hello), 0);
std::cout << "Hello message sent\n";
// 读取服务器的响应
read(sock, buffer, 1024);
std::cout << "Message from server: " << buffer << std::endl;
// 关闭socket
close(sock);
return 0;
}
```
在上述示例中,服务器端创建了一个socket并监听在8080端口上,当客户端连接时,服务器读取客户端发送的消息,然后发送一个问候消息,并关闭连接。客户端连接到服务器,发送一条消息,然后接收服务器的响应,最后关闭连接。
阅读全文