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

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

  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);

  }

  closesocket(sockConnect);

  }

  WSACleanup();

  return 0;

  }

  客户端程序代码:

  view plaincopy to clipboardprint?

  // 2009-06-28

  #pragma comment(lib,"ws2_32.lib")

  #include

  #include

  #include

  using namespace std;

  string strCurMsg="";

  void recvProc(SOCKET sockClient)

  {

  char msgRcv[100]={0};

  while(true)

  {

  if(SOCKET_ERROR==recv(sockClient,msgRcv,sizeof(msgRcv),0))

  {

  cout<<"\nHe is leaving";

  return;

  }

  if(msgRcv[0]!=’\0’)

  {

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

  strCurMsg+="He said: ";

  strCurMsg+=msgRcv;

  strCurMsg+=’\n’;

  strCurMsg+="input: ";

  system("cls");

  cout<

  }

  }

  }

(责任编辑:IT教学网)

更多

推荐计算机等级考试文章