编写一个C语言server端支持自定义的监听端口,client发送测试流并成功返回信息的代码
时间: 2024-05-01 17:18:37 浏览: 111
下面是一个使用C语言编写的server端支持自定义的监听端口,client发送测试流并成功返回信息的代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int server_socket, client_socket, addr_len;
char buffer[BUFFER_SIZE];
struct sockaddr_in server_addr, client_addr;
// 创建socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
// 初始化服务器地址
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// 绑定socket
if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听socket
if (listen(server_socket, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
printf("server is listening on port %d\n", PORT);
addr_len = sizeof(client_addr);
// 接收client连接并处理请求
while (1) {
client_socket = accept(server_socket, (struct sockaddr*)&client_addr, (socklen_t*)&addr_len);
if (client_socket < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// 读取client发送的测试流
while (read(client_socket, buffer, BUFFER_SIZE) > 0) {
printf("received message from client: %s\n", buffer);
// 发送成功返回消息
char msg[] = "success";
if (write(client_socket, msg, strlen(msg)) < 0) {
perror("write failed");
exit(EXIT_FAILURE);
}
}
close(client_socket);
}
close(server_socket);
return 0;
}
```
希望这个代码对你有帮助。
阅读全文