聊天室流程
1. 客户端建立
- 客户端连接服务器,并发送数据
- 通过splice函数,实现向stdin(输入数据流)定向到socket(零拷贝)
- 使用了非阻塞连接
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <poll.h>
#include <fcntl.h>
using namespace std;
#define BUFFER_SIZE 64
//设置非阻塞
int setnonblocking(int fd)
{
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option;
}
//非阻塞连接
int unblock_connet(const char* ip, int port, int time)
{
//服务器的地址结构
struct sockaddr_in server_address;
bzero(&server_address, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port);//端口
inet_pton(AF_INET, ip, &server_address.sin_addr);//ip
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
assert(sockfd >= 0);
int fdopt = setnonblocking(sockfd);//设置非阻塞
//此时是非阻塞
int ret = connect(sockfd, (sockaddr*)&server_address, sizeof(server_address));
if (ret == 0)//如果连接成功,恢复sockfd的阻塞属性,并立即返回
{
printf("connect with server immediately\n");
fcntl(sockfd, F_SETFL, fdopt);
return sockfd;
}
else if (ret == -1 && errno != EINPROGRESS)//连接没有立即建立,只有当errno==EINPROGRESS时才表示连接孩子进行,否则出错返回
{
printf("unblock connect not support\n");
return -1;
}
//这里说明connect连接还在进行,需要用select监听连接失败的sockfd上的可写事件
//当select返回后,利用getsockopt来读取错误码消除sockfd上的错误
//错误码==0,成功建立连接,否则失败
fd_set readfds;
fd_set writefds;
struct timeval timeout;
FD_ZERO(&writefds);
FD_SET(sockfd, &writefds);
timeout.tv_sec = time;
timeout.tv_usec = 0;
do
{
ret = select(sockfd + 1, NULL, &writefds, NULL, &timeout);
} while (ret == -1 && errno == EINTR);//有中断
if (ret == -1)
{
printf("connect error\n");
close(sockfd);
return -1;
}
else if (ret == 0)
{
printf("connect timeout\n");
close(sockfd);
return -1;
}
else
{
if (!FD_ISSET(sockfd, &writefds))
{
printf("no events on sockfd found\n");
close(sockfd);
return -1;
}
//通过getsockopt判断连接是否成功
int error = 0;
socklen_t len = sizeof(error);
if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
{
printf("get socket option failed\n");
close(sockfd);
return -1;
}
if (error != 0)//错误号为0,连接出错
{
printf("connection failed after select with the error: %d\n", error);
close(sockfd);
return -1;
}
//连接成功
printf("connection ready after select with the socket:%d\n", error);
fcntl(sockfd, F_SETFL, fdopt);
return sockfd;
}
}
int main(int argc, char* argv[])
{
if (argc <= 2)
{
printf("usage: %s ip_address port_number\n", basename(argv[0]));
return 1;
}
const char* ip = argv[1];
int port = atoi(argv[2]);
int sockfd = unblock_connet(ip, port, 10000);
//连接成功
if (sockfd != -1)
{
pollfd fds[2];
//注册文件描述符0(标准输入)和文件描述符sockfd上的可读事件
fds[0].fd = 0;
fds[0].events = POLLIN;
fds[0].revents = 0;
fds[1].fd = sockfd;
fds[1].events = POLLIN | POLLRDHUP;
fds[1].revents = 0;
char read_buf[BUFFER_SIZE];
int pipefd[2];
int ret = pipe(pipefd);
assert(ret != -1);
while (1)
{
ret = poll(fds, 2, -1);
if (ret < 0)
{
printf("poll failure\n");
break;
}
if (fds[1].revents & POLLRDHUP)
{
printf("server close the connection");
break;
}
else if (fds[1].revents & POLLIN)
{
memset(read_buf, '\0', BUFFER_SIZE);
recv(fds[1].fd, read_buf, BUFFER_SIZE - 1, 0);
printf("%s\n", read_buf);
}
if (fds[0].revents & POLLIN)
{
//使用splice将用户输入的数据直接写到sockfd上(零拷贝)
ret = splice(0, NULL, pipefd[1], NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE);
ret = splice(pipefd[0], NULL, sockfd, NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE);
}
}
close(sockfd);
return 0;
}
return 0;
}
2. 服务器建立
- 设置聊天室连接数量上限
- 允许多个客户端建立连接
- 客户端A发送的数据,又服务器转发给其他聊天室中的客户端
- 通过数组users[connfd]表示connfd的对应的数据
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <poll.h>
#include <fcntl.h>
using namespace std;
#define BUFFER_SIZE 64 //读缓冲区大小
#define USER_LIMIT 5 //最大用户数量
#define FD_LIMIT 65535 //文件描述符数量限制
//客户数据
struct client_data
{
sockaddr_in address;//客户端地址
char* write_buf;//待写到客户端的数据的位置
char buf[BUFFER_SIZE];//从客户端读入的数据
};
//设置非阻塞
int setnonblocking(int fd)
{
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option;
}
int main(int argc, char* argv[])
{
if (argc <= 2)
{
printf("usage: %s ip_address port_number\n", basename(argv[0]));
return 1;
}
const char* ip = argv[1];
int port = atoi(argv[2]);
int ret = 0;
//服务器地址设置
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port);//端口
inet_pton(AF_INET, ip, &server_address.sin_addr);
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
assert(listenfd >= 0);
ret = bind(listenfd, (struct sockaddr*)&server_address, sizeof(server_address));
assert(ret != -1);
ret = listen(listenfd, 5);
assert(ret != -1);
/*
创建users数组
每个可能的socket连接都可以获得一个这样的对象,并且socket的值(数组下标)可以直接用来索引socket连接对应的client_data对象,
这是将socket和客户数据关联的简单而有效的方式
*/
client_data* users = new client_data[FD_SETSIZE];
//尽管分配了足够多的client_data对象,但为了提高poll的性能,仍然需要限制用户数量
pollfd fds[USER_LIMIT + 1];
int user_counter = 0;
//最开始没有连接socket
for (int i = 1; i<=USER_LIMIT; ++i)
{
fds[i].fd = -1;
fds[i].events = 0;
}
//poll监听 监听socket
fds[0].fd = listenfd;
fds[0].events = POLLIN | POLLERR;
fds[0].revents = 0;
while (1)
{
ret = poll(fds, user_counter + 1, -1);
if (ret < 0)
{
printf("poll failure\n");
break;
}
for (int i = 0; i < user_counter + 1; ++i)
{
//有连接请求
if ((fds[i].fd == listenfd) && (fds[i].revents & POLLIN))
{
struct sockaddr_in client_address;
socklen_t client_addrLen = sizeof(client_address);
int connfd = accept(listenfd, (struct sockaddr*)&client_address, &client_addrLen);
if (connfd < 0)
{
printf("errno is : %d\n", errno);
continue;
}
//请求太多,关闭新到的连接
if (user_counter >= USER_LIMIT)
{
const char* info = "too many users\n";
printf("%s", info);
send(connfd, info, strlen(info), 0);
close(connfd);
continue;
}
//对于新的连接,同时修改fds和users数组,users[connfd]对应于新连接文件描述符connd的客户数据
user_counter++;
users[connfd].address = client_address;
setnonblocking(connfd);
fds[user_counter].fd = connfd;
fds[user_counter].events = POLLIN | POLLRDHUP | POLLERR;
fds[user_counter].revents = 0;
printf("comes a new user, now have %d users\n", user_counter);
}
else if (fds[i].revents & POLLERR)//出错
{
printf("get an error from %d\n", fds[i].fd);
char errors[100];
memset(errors, '\0', 100);
socklen_t len = sizeof(errors);
if (getsockopt(fds[i].fd, SOL_SOCKET, SO_ERROR, &errors, &len) < 0)
{
printf("get socket option failed\n");
}
continue;
}
else if (fds[i].revents & POLLHUP)
{
//如果客户端关闭连接,服务器也关闭对应的连接,并将用户总数-1
users[fds[i].fd] = users[fds[user_counter].fd];//删除就是覆盖,把最后一个覆盖给当前位置,user_count--就行
fds[i] = fds[user_counter];//poll监听数组也要更改
user_counter--;
i--;//删除了一个,i要往前面走一个
close(fds[i].fd);
printf("a client left\n");
}
else if (fds[i].revents & POLLIN)//有数据可读
{
int connfd = fds[i].fd;
memset(users[connfd].buf, '\0', BUFFER_SIZE);
ret = recv(connfd, users[connfd].buf, BUFFER_SIZE - 1, 0);
if (ret < 0)//如果读出错,关闭连接
{
if (errno != EAGAIN)
{
close(connfd);
users[fds[i].fd] = users[fds[user_counter].fd];
fds[i] = fds[user_counter];
user_counter--;
i--;
}
}
else
{
if (ret == 0)
{
}
else //接收到客户数据,通知其他socket连接准备写数据
{
printf("get %d bytes of client data %s from %d\n", ret, users[connfd].buf, connfd);
for (int j = 1; j <= user_counter; ++j)
{
if (fds[j].fd == connfd)//当前的连接socket不处理
{
continue;
}
fds[j].events |= ~POLLIN;
fds[j].events |= POLLOUT;
users[fds[j].fd].write_buf = users[connfd].buf;
}
}
}
}
else if (fds[i].revents & POLLOUT)
{
int connfd = fds[i].fd;
if (!users[connfd].write_buf)//有数据可写
{
continue;
}
ret = send(connfd, users[connfd].write_buf, strlen(users[connfd].write_buf), 0);
users[connfd].write_buf = NULL;//清空数据
//写完数据需要重新注册fds[i]的可读事件
fds[i].events |= ~POLLOUT;
fds[i].events |= POLLIN;
}
}
}
delete[] users;
close(listenfd);
return 0;
}