为什么 要在标题后面加个“阻塞”呢,因为系统为了增大并发,减小等待(阻塞),建立了另一种事件模式,后文将介绍,这里只介绍阻塞的模型。
阻塞服务器要干的事大致可以分为以下几步:
1.创建服务端监听连接
2.产生用户连接
3.接收用户请求
4.发送返回给用户
敲码过程如下:
设置监听地址与端口:
addr_server.sin_family = AF_INET; addr_server.sin_port = htons( port ); addr_server.sin_addr.s_addr = htonl( INADDR_ANY );
sock_server = socket( AF_INET, SOCK_STREAM, 0 ); flag = bind( sock_server, ( struct sockaddr* )&addr_server, sizeof( struct sockaddr ) ); if( flag < 0 ) { printf( "your bind is not ok\n" ); close( sock_server ); return 0; }
flag = listen( sock_server, 50 ); if( flag < 0 ) { printf( "your listen is not ok\n"); close( sock_server ); return 0; }
接收并产生用户连接:
sock_client = accept( sock_server, ( struct sockaddr* )&addr_client, &size ); if( sock_client <=0 ) { printf( "your accept is no ok\n"); close( sock_server ); return 0; }
接收用户数据:
flag = recv( sock_client, buffer, RECV_BUF_LEN, 0 ); if( flag <= 0 ) { printf( "your recv is no ok\n"); close( sock_client ); continue; }
校验数据合法性:
if( flag != 64 ) { printf( "your recv does follow the protocal\n"); close( sock_client ); continue; } if( buffer[31] || buffer[63] ) { printf( "your recv does follow the protocal\n"); close( sock_client ); continue; }
current = time(0); send( sock_client, ( const char* )¤t, sizeof( time_t), 0 );
printf( "your connection is ok\n"); printf( "now close your connection\n"); close( sock_client );
完整代码在这里:
下载