linux下套接字服务机和客户机通信的例程
时间: 2023-06-17 20:07:57 浏览: 111
下面是一个简单的 Linux 下套接字服务端和客户端通信的例程,使用 C 语言编写:
服务端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
char *hello = "Hello from server";
// 创建 socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置地址和端口
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// 绑定 socket
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 failed");
exit(EXIT_FAILURE);
}
// 接受连接请求
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// 读取客户端发送的消息
int valread = read(new_socket, buffer, BUFFER_SIZE);
printf("Client: %s\n", buffer);
// 发送消息给客户端
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
// 关闭 socket
close(new_socket);
close(server_fd);
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
char buffer[BUFFER_SIZE] = {0};
char *hello = "Hello from client";
// 创建 socket
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
// 设置地址和端口
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// 将 IP 地址转换为网络字节序
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) {
printf("\nInvalid address/ Address not supported \n");
return -1;
}
// 连接到服务器
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
// 发送消息给服务器
send(sock, hello, strlen(hello), 0);
printf("Hello message sent\n");
// 读取服务器发送的消息
int valread = read(sock, buffer, BUFFER_SIZE);
printf("Server: %s\n", buffer);
// 关闭 socket
close(sock);
return 0;
}
```
这个例程简单地演示了服务端和客户端通过套接字进行通信的过程。服务端创建一个 socket 并监听端口,等待客户端连接。客户端创建一个 socket 并连接到服务端。服务端和客户端之间通过 send() 和 read() 函数进行消息的发送和接收。最后,服务端和客户端关闭它们的 socket。
阅读全文