accept函数使用例子
时间: 2023-10-18 10:21:05 浏览: 92
AcceptEx函数的例子
5星 · 资源好评率100%
下面是一个使用accept函数的例子:
```
#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 MAX_CONNECTIONS 5
int main() {
int server_socket, new_socket, valread;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024] = {0};
const char *hello = "Hello from server!";
// Create socket
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("Failed to create socket");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Bind socket to port
if (bind(server_socket, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("Failed to bind socket");
exit(EXIT_FAILURE);
}
// Listen for connections
if (listen(server_socket, MAX_CONNECTIONS) < 0) {
perror("Failed to listen for connections");
exit(EXIT_FAILURE);
}
printf("Server is listening on port %d\n", PORT);
// Accept incoming connections
if ((new_socket = accept(server_socket, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("Failed to accept connection");
exit(EXIT_FAILURE);
}
printf("New connection established\n");
// Send message to client
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
// Receive message from client
valread = read(new_socket, buffer, 1024);
printf("%s\n", buffer);
return 0;
}
```
这个例子创建一个TCP服务器,监听指定的端口,等待客户端连接。当一个客户端连接成功后,使用accept函数接受连接,建立一个新的socket用于与客户端通信。随后,服务器向客户端发送一条消息,接收客户端的回复,并打印出来。
阅读全文