socket 开发范型

 原始文章参考:

http://www.codeproject.com/KB/IP/server_client_sockets.aspx

提供了几个简单的基于socket的client、server实例代码。

 

1)对于server来说,开发范型是:

// Initialize Winsock WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2,2), &wsaData); // Create a SOCKET for connecting to server SOCKET ConnectSocket; ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // The sockaddr_in structure specifies the address family, // IP address, and port of the server to be connected to. struct sockaddr_in serverIPAddr; serverIPAddr.sin_family = AF_INET; serverIPAddr.sin_addr.s_addr = inet_addr( "127.0.0.1" ); serverIPAddr.sin_port = htons( 27015 ); // bind to an address and a port iResult = bind( ConnectSocket, (SOCKADDR*) &serverIPAddr, sizeof(serverIPAddr) ); // wait for client connection iResult = listen(ConnectSocket, SOMAXCONN); // 实际上,这里收到一个客户请求的socket连接之后, // 应该起新线程,处理send、recv等事宜。 SOCKET AcceptSocket=SOCKET_ERROR; AcceptSocket=accept(ConnectSocket, NULL,NULL); // send or recieve data iResult = send(AcceptSocket, msg, strlen(msg),0); iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0); // cleanup closesocket(ConnectSocket); WSACleanup();

简化就是:

WSAStartup-->socket-->connect-->send-->[recv]-->[shutdown]-->closesocket-->WSACleanup

 

2)对于client来说,开发范型是:

WSADATA wsaData; SOCKET ConnectSocket; struct sockaddr_in clientService; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2,2), &wsaData); // Create a SOCKET for connecting to server ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // The sockaddr_in structure specifies the address family, // IP address, and port of the server to be connected to. clientService.sin_family = AF_INET; clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" ); clientService.sin_port = htons( DEFAULT_PORT ); // Connect to server. iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) ); // Send an initial buffer iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 ); // Receive until the peer closes the connection do { iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0); } while( iResult > 0 ); // shutdown the connection since no more data will be sent iResult = shutdown(ConnectSocket, SD_SEND); // cleanup closesocket(ConnectSocket); WSACleanup();

简化就是:

WSAStartup-->socket-->bind-->listen-->accept-->[send]-->recv-->[shutdown]-->closesocket-->WSACleanup

 

3)当然这两个范型是最简化的、基于阻塞的、纯粹同步的范型。实际开发的时候,需要考虑的至少有如下几个问题:

基于select或者event的异步;非阻塞;多线程(同步或者异步)。

这些也是下一步学习的重点。

你可能感兴趣的:(多线程,server,Stream,socket,null,structure)