资源描述:
《基于socket简易聊天程序》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、简单的socket程序2010-01-1322:18虽然很简单,但还是调试了很长时间。本科时候接触过socket——那个帅帅的刘老师的课,现在重新再捡起来。程序中专门建立一个FunThread线程用来接收数据,实现双向通信,也可以连续发送、连续接收。代码贴上来,如果还能保留VAView那样的颜色区别就好看了,但是试了好几遍都不行server:#include#include#definePORT 6000//服务器端口#defineMSGSIZE 1024//收发缓冲区的大小#pragmacomment(lib,"ws2_32
2、.lib")//链接静态库DWORDWINAPIFunThread(LPVOID);//创建一个线程,专门用来接收数据SOCKET sClient;//连接所用套节字SOCKET sListen;//监听套接字SOCKADDR_INclient;//保存客户的地址信息int iaddrSize=sizeof(SOCKADDR_IN);intmain(){WSADATA wsaData;SOCKADDR_INlocal;char s_Message[MSGSIZE];//收发缓冲区WSAStartup(0x0202,&wsaData);
3、//InitializeWindowssocketlibrarysListen=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);//创建服务器监听套节字。TCP协议local.sin_family=AF_INET;//AF_INET指明使用TCP/IP协议族local.sin_port=htons(PORT);//指明连接服务器的端口号local.sin_addr.s_addr=htonl(INADDR_ANY);//自动获取本机地址bind(sListen,(structsockaddr)&local,otherstaffoftheCentre.D
4、uringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,S
5、henmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersandsizeof(SOCKADDR_IN));//地址绑定到套接字listen(sListen,1);//开始监听sClient=accept(sListen,(structsockaddr)&client,&iaddrSize);//建立连接printf("Accepteclient:%s:%d",inet_ntoa(client.s
6、in_addr),ntohs(client.sin_port));HANDLEhThread=CreateThread(NULL,0,FunThread,0,0,0);//创建接收线程CloseHandle(hThread);while(TRUE){ printf("ServerSend:"); //从键盘输入 gets(s_Message); //发送数据 send(sClient,s_Message,strlen(s_Message),0);}return0;}DWORDWINAPIFunThread(LPVOID){
7、charc_Message[MSGSIZE];//收发缓冲区intret;//接收字节的个数while(TRUE){ ret=recv(sClient,c_Message,MSGSIZE,0);//接收数据 if(ret==SOCKET_ERROR) { printf("clientisclosed!"); sClient=accept(sListen,(structsockaddr)&client,&iaddrSize);//重新开始监听