C++ socket开发1

服务端

setlocale(LC_ALL,"Chinese-simplified");
 WORD wVersionRequested;
 WSADATA wsaData;
 int err;

 wVersionRequested  = MAKEWORD(1,1);
 err = WSAStartup(wVersionRequested,&wsaData);
 if(err !=0 )
 {
  return;
 }
 if(LOBYTE(wsaData.wVersion)!=1 || HIBYTE(wsaData.wVersion) !=1)
 {
  WSACleanup();
  return;
 }
 SOCKET sockSrv = socket(AF_INET,SOCK_STREAM,0);
 if (INVALID_SOCKET == sockSrv)
 {
  return;
 }
 SOCKADDR_IN addrsrv;
 addrsrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
 addrsrv.sin_family = AF_INET;
 addrsrv.sin_port = htons(6000);

 if(SOCKET_ERROR ==bind(sockSrv,(SOCKADDR*)&addrsrv,sizeof(SOCKADDR)))
 {
  return;
 }
 listen(sockSrv,5);

 SOCKADDR_IN addrClient;
 int len = sizeof(SOCKADDR);
 while(1)
 {
  SOCKET sockConn =  accept(sockSrv,(SOCKADDR*)&addrClient,&len);
  /*const int iBufferSize = 1024;
  char recvBuf[iBufferSize]={0};
  memset(recvBuf,0,iBufferSize);*/
  const int iBufferSize = 1024;
  char recvBuf[iBufferSize];
  recv(sockConn,recvBuf,iBufferSize,0);
        RequestStruct  rs;
  memset( &rs,0,sizeof(rs));
  memcpy( &rs, recvBuf, sizeof(recvBuf) );
  client_OnStringData(rs);
 }

 

客户端:

WORD wVersionRequested;
 WSADATA wsaData;
 int err;

 wVersionRequested  = MAKEWORD(1,1);
 err = WSAStartup(wVersionRequested,&wsaData);
 if(err !=0 )
 {
  return;
 }
 if(LOBYTE(wsaData.wVersion)!=1 || HIBYTE(wsaData.wVersion) !=1)
 {
  WSACleanup();
  return;
 }
 m_sockClient = socket(AF_INET,SOCK_STREAM,0);
 
 SOCKADDR_IN addrsrv;
 addrsrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
 addrsrv.sin_family = AF_INET;
 addrsrv.sin_port = htons(6000);
 
 connect(m_sockClient,(SOCKADDR*)&addrsrv,sizeof(SOCKADDR));
 {
  /*memcpy( rs.QueType, "MSG_CU_VIDEO_REQ", sizeof("MSG_CU_VIDEO_REQ") );
  send(m_sockClient,(char *)&rs,sizeof(RequestStruct),0);*/
  send(m_sockClient,(char *)m_requestStruct,sizeof(RequestStruct),0);
  
  /*RequestStruct  *rs;
  memcpy( rs.QueType, "MSG_CU_VIDEO_REQ", sizeof("MSG_CU_VIDEO_REQ") );
  send(m_sockClient,(char *)&rs,sizeof(RequestStruct),0);*/
 }

posted on 2013-10-12 08:20  松原蔡晓冬  阅读(165)  评论(0编辑  收藏  举报

导航