网络编程基础

网络编程基础
Socket 编程最基本的模型就是 Berkeley Socket

          具体的实现也就是按这个流程图来做的,这里重点是服务端的实现。

int APIENTRY _tWinMain(HINSTANCE hInstance,
                      HINSTANCE hPrevInstance,
                      LPTSTR     lpCmdLine,
                     
int         nCmdShow)
{
            ofstream logfile(
" LogFile.txt " );
           
// Initialize winsock
            WSADATA wsaData;
            
int iResult = WSAStartup( MAKEWORD( 2 , 2 ), & wsaData);
            
if (iResult != NO_ERROR)
             {
                     logfile
<< " Error at WSAStartup() " ;    
                     logfile.close();
                    
return 1 ;
             }
            
else     
                    logfile
<< " Initialize WSAStartup OK! " ;
    
             
// Create a socket.
             SOCKET serverSocket;
             serverSocket
= socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

             
if (serverSocket == INVALID_SOCKET)
              {    
                      logfile
<< " Error at socket(): " << WSAGetLastError() << endl;;
                      logfile.close();
                      WSACleanup();
                      
return 1 ;
              }
             
else
             {
                      logfile
<< " Create socket OK! " ;
              }

            
// Bind the socket.
              sockaddr_in service;

              service.sin_family
= AF_INET;
              service.sin_addr.s_addr
= inet_addr(HostIp.c_str());
              service.sin_port
= htons(PORT);

              
if (bind(serverSocket,(SOCKADDR * ) & service, sizeof (service)) == SOCKET_ERROR)
              {
                       logfile
<< " bind() failed " << GetLastError() << endl;
                       closesocket(serverSocket);
                       logfile.close();
                      
return 1 ;
              }
             
else
              {
             logfile
<< " Binding OK! " << endl;
               }
    
    
              
// Listen on the socket.
                if (listen(serverSocket, 1 ) == SOCKET_ERROR)
               {
                       logfile
<< " Error listening on socket " << GetLastError() << endl;
                       logfile.close();
                }
               
else
                {
                       logfile
<< " Listening... " << endl;
                 }

                
// Accept connections.
                 SOCKET clientSocket;
                 sockaddr_in clientAddr;
                
int clientAddrLen = sizeof (clientAddr);
   
                
while ( true )
                 {
                            clientSocket
= SOCKET_ERROR;
                           
while (clientSocket == SOCKET_ERROR)
                            {
                                   clientSocket
= accept(serverSocket,( struct sockaddr * ) & clientAddr, & clientAddrLen);      
                             }
                            ReceiveData(clientSocket);    
                   }   

                   closesocket(serverSocket);
                   closesocket(clientSocket);

                  
return 0 ;
}

// Receive the data
void ReceiveData(SOCKET & clientSocket)
{    
            
int bytesSent;
            
int bytesRecv = SOCKET_ERROR;
            
string sendbuf = "" ;
            
char recvbuf[ 32 ] = "" ;
    
            
while (bytesRecv == SOCKET_ERROR)
             {
                       bytesRecv
= recv(clientSocket,recvbuf, 32 , 0 );
    
                        sendbuf
= " Received: " + ( string )recvbuf;
                        bytesSent
= send(clientSocket,sendbuf.c_str(),(unsigned int )(sendbuf.size()), 0 );

                        bytesRecv
= SOCKET_ERROR;
                        memset(recvbuf,
'\0',32);
             }
            return;
}

          在接收客户端发来数据的地方要做成死循环,如果需要断开连接,则由客户断发送特定的消息然后进行处理。还有需要注意的是上面的HostIp是本机的IP地址,PORT是套接字需要绑定的端口。

你可能感兴趣的:(网络编程基础)