1.select客户端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 9999
#define IP "192.168.125.216"
int main() {
int cfd = socket(AF_INET,SOCK_STREAM,0);
if (cfd == -1)
{
perror("socket");
return -1;
}
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(PORT);
cin.sin_addr.s_addr = inet_addr(IP);
if (connect(cfd,(struct sockaddr*)&cin,sizeof(cin)) == -1)
{
perror("connect");
return -1;
}
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(0,&readfds);
FD_SET(cfd,&readfds);
while (1)
{
fd_set tempfds = readfds;
int res = select(cfd+1,&tempfds,NULL,NULL,NULL);
if (res == -1)
{
perror("select");
return -1;
}else if (res == 0)
{
printf("timeout\n");
}
if (FD_ISSET(0,&tempfds))
{
char buf[128];
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf) -1] = 0;
if (send(cfd,buf,sizeof(buf),0) == -1 )
{
perror("send");
return -1;
}
if (strcmp(buf,"exit") == 0)
{
break;
}
}
if (FD_ISSET(cfd,&tempfds))
{
char buf[128];
int res = recv(cfd,buf,sizeof(buf),0);
if (res == 0)
{
printf("服务器已下线\n");
break;
}
printf("%s\n",buf);
}
}
return 0;
}
2.poll服务器
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <poll.h>
#define PORT 9999
#define MAX_CLIENTS 10
int main() {
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd == -1) {
perror("socket");
return -1;
}
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = INADDR_ANY;
if (bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) == -1) {
perror("bind");
close(sfd);
return -1;
}
if (listen(sfd, MAX_CLIENTS) == -1) {
perror("listen");
close(sfd);
return -1;
}
struct pollfd fds[MAX_CLIENTS + 1];
memset(fds, 0, sizeof(fds));
fds[0].fd = sfd;
fds[0].events = POLLIN;
int nfds = 1;
printf("Server is listening on port %d...\n", PORT);
while (1) {
int numReady = poll(fds, nfds, -1);
if (numReady == -1) {
perror("poll");
break;
}
if (fds[0].revents & POLLIN) {
int cfd = accept(sfd, NULL, NULL);
if (cfd == -1) {
perror("accept");
} else {
printf("New client connected\n");
fds[nfds].fd = cfd;
fds[nfds].events = POLLIN;
nfds++;
}
numReady--;
}
for (int i = 1; i < nfds && numReady > 0; i++) {
if (fds[i].revents & POLLIN) {
char buf[128];
int bytesRead = recv(fds[i].fd, buf, sizeof(buf) - 1, 0);
if (bytesRead <= 0) {
if (bytesRead == 0) {
printf("Client disconnected\n");
} else {
perror("recv");
}
close(fds[i].fd);
fds[i] = fds[nfds - 1];
nfds--;
} else {
buf[bytesRead] = '\0';
printf("Received from client: %s\n", buf);
}
numReady--;
}
}
}
close(sfd);
return 0;
}