控制台聊天程序服务器端代码(2)

http://www.itjxue.com  2015-07-17 00:54  来源:未知  点击次数: 

  if ( LOBYTE( wsaData.wVersion ) != 1||

  HIBYTE( wsaData.wVersion ) != 1) {

  WSACleanup( );

  return 1;

  }

  SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

  sockaddr_in addrSrv;

  memset(&addrSrv,0,sizeof(addrSrv));

  addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);

  addrSrv.sin_family=AF_INET;

  addrSrv.sin_port=htons(5000);

  if(bind(sockSrv,(sockaddr*)&addrSrv,sizeof(sockaddr))==SOCKET_ERROR)

  {

  cout<<"bind error"<

  }

  if(listen(sockSrv,5)==SOCKET_ERROR)

  {

  cout<<"listen error"<

  }

  SOCKADDR_IN addrClient;

  int len=sizeof(sockaddr);

  while(true)

  {

  cout<<"Waiting .....";

  SOCKET sockConnect=accept(sockSrv,(sockaddr*)&addrClient,&len);

  if(sockConnect==INVALID_SOCKET)

  {

  cout<<"invalid socket"<

  return 0;

  }

  else

  {

  cout<<"He is coming\n";

  }

  CreateThread(NULL,0,

  (LPTHREAD_START_ROUTINE)recvProc,(void*)sockConnect,

  0,NULL);

  while(true)

  {

  char buf[100]={0};

  strCurMsg+="input: ";

  system("cls");

  cout<

  cin.getline(buf,100);

  strCurMsg.erase(strCurMsg.end()-7,strCurMsg.end());

  strCurMsg+="You said:";

  strCurMsg+=buf;

  strCurMsg+=’\n’;

  send(sockConnect,buf,sizeof(buf),0);

  }

(责任编辑:IT教学网)

更多

推荐计算机等级考试文章