服务器客户机聊天程序(非阻塞套接字)
serve.cpp
#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main()
{
int sfp, nfp;
struct sockaddr_in s_add, c_add;
socklen_t sin_size;
unsigned short portnum = 10051;
printf("Hello I am a server, Welcome to connect me !\r\n");
sfp = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == sfp)
{
printf("socket fail !\r\n");
return -1;
}
printf("socket ok !\r\n");
int on = 1;
setsockopt(sfp, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); //允许地址的立即重用
bzero(&s_add, sizeof(struct sockaddr_in));
s_add.sin_family = AF_INET;
s_add.sin_addr.s_addr = htonl(INADDR_ANY); //绑定本机所有网卡
s_add.sin_port = htons(portnum);
if(-1 == bind(sfp, (struct sockaddr *)(&s_add),sizeof(s_add)))
{
printf("bind fail: %d!\r\n", errno);
return -1;
}
printf(