#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/socket.h> #include <arpa/inet.h>
#define RCV_BUF_LEN 200
int main( int ac, char **av ) { int sock; int client_Sock; int ret; char inputBuf[200]; char recvBuf[RCV_BUF_LEN]; struct sockaddr_in svrAddr; int i; int val;
/** 创建监听套接字 **/ if ( (sock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ){ printf("socket error!\n"); return -1; }
/** 指定监听端口和地址 **/ memset( &svrAddr, 0x00, sizeof(svrAddr) ); svrAddr.sin_family =AF_INET; svrAddr.sin_addr.s_addr = htonl( INADDR_ANY ); svrAddr.sin_port = htons( 2010 );
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR, (char *)&val, sizeof(val) );
/** 绑定监听套接字和端口 **/ if ( bind(sock, (struct sockaddr *)&svrAddr, sizeof(svrAddr)) != 0 ){ printf("bind error!\n"); return -1; }
/** 监听套接字 */ if ( listen( sock, 10 ) != 0 ){ printf("listen error!\n"); return -1; }
while( 1 ){ /** 等待连接请求 **/ printf("等待客户端连接请求..\n"); if ( (client_Sock = accept( sock, NULL, 0 )) < 0 ){ printf("accept error!\n"); return -1; }
printf("客户端已连入..\n");
while( 1 ){ memset( recvBuf, 0x00, RCV_BUF_LEN ); ret = recv( client_Sock, recvBuf, RCV_BUF_LEN, 0 ); recvBuf[strlen(recvBuf) - 1] = 0; if ( ret > 0 ){ printf("接收到: [%s]\n", recvBuf); for( i = 0; i < strlen(recvBuf); i++ ){ if ( recvBuf[i] > 96 && recvBuf[i] < 123 ){ recvBuf[i] -= 32; } }
ret = send( client_Sock, recvBuf, strlen(recvBuf), 0 ); if ( ret > 0 ){ printf("处理并返回成功..\n"); } else if ( ret < 0 ){ printf("返回客户端错误..\n"); } } else if ( ret == 0 ){ printf("客户端断开..\n"); break; } else{ printf("rcv error!\n"); break; } }
}
return 0; } |