基于C++的简单示例程序,本地socket通信,含服务端和客户端
时间: 2024-01-30 07:02:07 浏览: 92
以下是一个简单的示例程序,使用C++语言实现本地socket通信,包括服务端和客户端。该程序可以在Linux和Windows等操作系统上运行。
服务端代码:
```c++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
// 创建socket
int server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (server_sockfd == -1) {
perror("socket error");
exit(EXIT_FAILURE);
}
// 绑定地址
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(server_sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("bind error");
exit(EXIT_FAILURE);
}
// 监听连接请求
if (listen(server_sockfd, 5) == -1) {
perror("listen error");
exit(EXIT_FAILURE);
}
// 等待客户端连接
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int client_sockfd = accept(server_sockfd, (struct sockaddr*)&client_addr, &client_addr_len);
if (client_sockfd == -1) {
perror("accept error");
exit(EXIT_FAILURE);
}
// 接收客户端消息
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
if (recv(client_sockfd, buffer, sizeof(buffer), 0) == -1) {
perror("recv error");
exit(EXIT_FAILURE);
}
printf("Received message: %s\n", buffer);
// 发送消息给客户端
const char* message = "Hello, client!";
if (send(client_sockfd, message, strlen(message), 0) == -1) {
perror("send error");
exit(EXIT_FAILURE);
}
// 关闭socket
close(client_sockfd);
close(server_sockfd);
return 0;
}
```
客户端代码:
```c++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
// 创建socket
int client_sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (client_sockfd == -1) {
perror("socket error");
exit(EXIT_FAILURE);
}
// 连接服务器
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(client_sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("connect error");
exit(EXIT_FAILURE);
}
// 发送消息给服务器
const char* message = "Hello, server!";
if (send(client_sockfd, message, strlen(message), 0) == -1) {
perror("send error");
exit(EXIT_FAILURE);
}
// 接收服务器消息
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
if (recv(client_sockfd, buffer, sizeof(buffer), 0) == -1) {
perror("recv error");
exit(EXIT_FAILURE);
}
printf("Received message: %s\n", buffer);
// 关闭socket
close(client_sockfd);
return 0;
}
```
服务端和客户端之间的通信流程如下:
1. 服务端创建socket,并绑定地址;
2. 服务端监听连接请求;
3. 客户端创建socket,并连接服务器;
4. 客户端向服务器发送消息;
5. 服务端接收客户端消息,并发送消息给客户端;
6. 客户端接收服务端消息;
7. 客户端关闭socket;
8. 服务端关闭socket。
阅读全文