这里实现了一个简单的基于 tcp 的服务端与客户端通信的程序,如下:
服务器端:
void CTwinsocketDlg::OnBtnStartServer() { // TODO: Add your control notification handler code here WORD tVersion = MAKEWORD(1,1); WSADATA tData; int er = WSAStartup(tVersion, &tData); if( er != 0) return ; if(LOBYTE(tData.wVersion) != 1 || HIBYTE(tData.wVersion) != 1){ WSACleanup(); return; } SOCKET serverSock = socket(AF_INET, SOCK_STREAM, 0); if(serverSock == INVALID_SOCKET){ WSACleanup(); return; } sockaddr_in tSockAddr; tSockAddr.sin_family = AF_INET; tSockAddr.sin_port = htons(7000); tSockAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); bind(serverSock, (SOCKADDR *)&tSockAddr, sizeof(SOCKADDR)); listen(serverSock, 3); SOCKADDR_IN tClientAddr; int tLen = sizeof(SOCKADDR); SOCKET tClientSock = accept(serverSock, (SOCKADDR *)&tClientAddr, &tLen); if(tClientSock == INVALID_SOCKET){ closesocket(serverSock); WSACleanup(); return; } char tBuf[100]; memset(tBuf,0x0,100); sprintf(tBuf, "welcome, %s./0",inet_ntoa(tClientAddr.sin_addr)); send(tClientSock, tBuf, strlen(tBuf),0); char tRecvData[100]; recv(tClientSock, tRecvData,100,0); CString ts; ts.Format("client say : %s", tRecvData ); MessageBox(ts); closesocket(tClientSock); closesocket(serverSock); WSACleanup(); }
客户端:
void CTsocketclientDlg::OnBtnStartClient() { // TODO: Add your control notification handler code here WORD tVersion = MAKEWORD(1,1); WSADATA tData; int er = WSAStartup(tVersion, &tData); if( er != 0) return; if(LOBYTE(tData.wVersion) != 1 || HIBYTE(tData.wVersion) != 1){ WSACleanup(); return; } SOCKET tClientSock = socket(AF_INET, SOCK_STREAM, 0); if(tClientSock == INVALID_SOCKET){ WSACleanup(); return; } SOCKADDR_IN tServerAddr; tServerAddr.sin_family = AF_INET; tServerAddr.sin_port = htons(7000); tServerAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); connect(tClientSock, (SOCKADDR *)&tServerAddr, sizeof(SOCKADDR)); char tBuf[100]; recv(tClientSock, tBuf,100,0); CString ts; ts.Format("server say : %s", tBuf); MessageBox(ts); memset(tBuf,0x0,100); sprintf(tBuf, " I am the superman./0"); send(tClientSock, tBuf, strlen(tBuf), 0); closesocket(tClientSock); WSACleanup(); }