hello world

随笔 - 2, 文章 - 63, 评论 - 0, 引用 - 0
数据加载中……

Socket阻塞通信

server.cpp #include #include #pragma comment(lib,"WS2_32.lib") void main() { WSADATA wsd; SOCKET server; //服务器socket SOCKADDR_IN addrSrv; char sendBuf[100]; char recvBuf[100]; SOCKADDR_IN addrClient; SOCKET client; //连接的客户端socket int len; if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { printf("start up failed!\n"); return ; } server=socket(AF_INET,SOCK_STREAM,0); //创建socket addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY); //设置地址 addrSrv.sin_family=AF_INET; addrSrv.sin_port=htons(6000); //设置端口号 bind(server,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)); //绑定 listen(server,5); //设置最多连接数 len=sizeof(SOCKADDR); while(1) { client=accept(server,(SOCKADDR*)&addrClient,&len); //接收客户端连接 sprintf(sendBuf,"Welcome %s ", inet_ntoa(addrClient.sin_addr)); send(client,sendBuf,strlen(sendBuf)+1,0); //发送信息客户端 recv(client,recvBuf,100,0); //接收客户端数据 printf("%s\n",recvBuf); closesocket(client); } closesocket(client); //关闭连接 WSACleanup(); } client.cpp #include #include #pragma comment(lib,"WS2_32.lib") void main() { int call = 0; int result = 0; while(1) { printf("\n\n请输入命令:\n"); printf("\t1:发起连接\n"); printf("\t2:发送数据\n"); printf("\t3:关闭连接\n"); printf("\t4:重新连接\n"); printf("\t0:关闭程序\n"); scanf("%d",&call); try{ switch(call) { case 1: printf("发起连接\n"); WSADATA wsd; SOCKET sockClient; //客户端socket SOCKADDR_IN addrSrv; char recvBuf[100]; char sendbuf[100]; if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { printf("start up failed!\n"); return ; } sockClient=socket(AF_INET,SOCK_STREAM,0); //创建socket addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); addrSrv.sin_family=AF_INET; addrSrv.sin_port=htons(6000); connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)); //连接服务器端 recv(sockClient,recvBuf,100,0); //接收服务器端数据 printf("%s\n",recvBuf); break; case 2: printf("请输入要发送的文字\n"); scanf("%s",&sendbuf); printf("%s\n",sendbuf); result = send(sockClient,sendbuf,50,0); //向服务器端发送数据 printf("操作结果:%d\n",result); break; case 3: result = closesocket(sockClient); printf("操作结果:%d\n",result);//关闭连接 WSACleanup(); printf("连接已经关闭\n"); break; case 4: printf("重新连接\n");//此处功能暂未实现 break; case 0: return; default: break; } }catch(Exception e) { } } }

posted on 2014-03-25 22:45 听风 阅读(141) 评论(0)  编辑  收藏 所属分类: C++


只有注册用户登录后才能发表评论。


网站导航: