服务端代码
#define WIN32_LEAN_AND_MEAN #include <winsock2.h> #include <windows.h> #include <stdlib.h> #include <stdio.h> //#pragma comment (lib, "ws2_32.lib") //加载 ws2_32.dll using namespace std; void main() { int nRet; WSADATA wsaData; WSAStartup( MAKEWORD(2, 2), &wsaData); //Windos 使用socket要有这一句 printf("Hello Socket "); SOCKET servSock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP); //绑定套接字 sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); //每个字节都用0填充 sockAddr.sin_family = PF_INET; //使用IPv4地址 sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //具体的IP地址 sockAddr.sin_port = htons(1555); //端口 bind(servSock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)); //进入监听状态 listen(servSock, 20); SOCKET clntSock; while(1) { //接收客户端请求 SOCKADDR clntAddr; //timeval timeout={0,0}; //nRet = select(maxfdp, &readfds, &writefds, &errorfds, &timeout); int nSize = sizeof(SOCKADDR); clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize); printf("打开客户端socket。。。 "); //向客户端发送数据 char *str = "Hello World!"; send(clntSock, str, strlen(str)+sizeof(char), NULL); } //关闭套接字 closesocket(clntSock); closesocket(servSock); //system("pause"); WSACleanup();//Windos 使用socket要有这一句 }
客户端代码
#include <stdio.h> #include <stdlib.h> #include <WinSock2.h> #pragma comment(lib, "ws2_32.lib") //加载 ws2_32.dll /*客户端代码*/ int main(){ //初始化DLL WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); //创建套接字 SOCKET sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); //向服务器发起请求 sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); //每个字节都用0填充 sockAddr.sin_family = PF_INET; sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); sockAddr.sin_port = htons(1555); connect(sock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)); //接收服务器传回的数据 char szBuffer[MAXBYTE] = {0}; recv(sock, szBuffer, MAXBYTE, NULL); //输出接收到的数据 printf("Message form server: %s ", szBuffer); //关闭套接字 closesocket(sock); //终止使用 DLL WSACleanup(); system("pause"); return 0; }