Linux下网络编程-简易poll服务器和客户端
简易poll服务器:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <poll.h>int main(int argc, char *argv[])
{int serv_sock=socket(PF_INET, SOCK_STREAM, 0);struct sockaddr_in serv_adr;memset(&serv_adr, 0, sizeof(serv_adr));serv_adr.sin_family=AF_INET;serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);serv_adr.sin_port=htons(atoi(argv[1]));if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr))==-1)error_handling("bind() error");if(listen(serv_sock, 5)==-1)error_handling("listen() error");struct pollfd fds[1024];for(int i=0;i<1024;i++){fds[i].fd=-1;fds[i].events=POLLIN;}fds[0].fd=serv_sock;int maxfd=0;while (1) {if(poll(fds, maxfd+1, -1)==-1){perror("select");exit(0);}if(fds[0].revents&POLLIN){struct sockaddr_in sockcli;socklen_t len = sizeof(sockcli);int connfd = accept(serv_sock, (struct sockaddr*)&sockcli, &len);int i;for(i=0;i<1024;i++){if(fds[i].fd==-1){fds[i].fd=connfd;break;}}maxfd=i>maxfd?i:maxfd;}for(int i=1;i<=maxfd;i++){if(fds[i].revents&POLLIN){char buf[128];int ret = read(fds[i].fd, buf, sizeof(buf));if(ret == -1){perror("read");exit(0);}else if(ret == 0){printf("对方已经关闭了连接...\n");close(fds[i].fd);fds[i].fd = -1;}else{printf("客户端say: %s\n", buf);write(fds[i].fd, buf, strlen(buf)+1);}}}}close(serv_sock);return 0;
}
简易客户端:
#include <netinet/in.h>
#include <cstdio>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <poll.h>
using namespace std;int main()
{int Client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if (Client == -1){cout << "创建失败" << endl;close(Client);return -1;}const char* ip = "127.0.0.1";unsigned short port=9527;sockaddr_in addrServer;addrServer.sin_addr.s_addr = inet_addr(ip);addrServer.sin_port = htons(port);addrServer.sin_family = AF_INET;if (connect(Client, (sockaddr*)&addrServer, sizeof(addrServer))== -1){cout << "连接失败" << endl;close(Client);return -1;}cout << "连接服务器成功" << endl;char rec[1024];char se[1024];while(1){memset(rec, 0, sizeof(rec));memset(se, 0, sizeof(se));scanf("%s", se);if (strcmp(se, "quit") == 0 || strcmp(se, "exit") == 0)break;if (send(Client, se, sizeof(se), 0) < 0)break;cout << "发送:" << se << endl;if (recv(Client, rec, sizeof(rec), 0) < 0)break;cout << "接收:" << rec << endl;}cout << "已与服务端断开连接" << endl;close(Client);return 0;
}