写出基于tcp协议的服务端c语言编程
时间: 2024-04-29 14:26:10 浏览: 46
可以,您可以参考如下代码实现基于tcp协议的服务端C语言编程:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 8080
int main(int argc, char const *argv[]) {
int server_fd, client_fd, valread;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from server";
// Creating socket file descriptor
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);
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
if ((client_fd = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
valread = read(client_fd, buffer, 1024);
printf("%s\n", buffer);
send(client_fd, hello, strlen(hello), 0);
printf("Hello message sent\n");
return 0;
}
```
该代码实现了一个简单的TCP协议的服务端。在该程序中,使用socket()函数创建了一个套接字,bind()绑定了一个端口号,listen()开始监听,并使用accept()函数等待客户端连接。当接收到客户端的连接请求时,程序通过read()函数读取客户端发送的数据并输出到屏幕上,然后通过send()函数向客户端发送“Hello from server”消息。
阅读全文