//InitSock.h #pragma once #include <WinSock2.h> #pragma comment(lib,"WS2_32") class CInitSock { public: CInitSock(BYTE minorVer = 2,BYTE majorVER = 2) { //初始化WS2_32.dll WSADATA wsaData; WORD sockVersion = MAKEWORD(minorVer,majorVER); if(::WSAStartup(sockVersion,&wsaData)!=0) exit(0); } ~CInitSock() { ::WSACleanup(); } }; //TCPServer.cpp #include "InitSock.h" #include <stdio.h> CInitSock initSock; //初始化Winsock库 int main() { //创建套接字 SOCKET sListen = ::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (sListen == INVALID_SOCKET) { printf("Failed socket()\n"); return 0; } //填充sockaddr_in结构 sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(4567); sin.sin_addr.S_un.S_addr = INADDR_ANY; //绑定这个套接字到一个本地地址 if (::bind(sListen,(LPSOCKADDR)&sin,sizeof(sin)) == SOCKET_ERROR) { printf("Failed bind()\n"); return 0; } //进入监听模式 if (::listen(sListen,2) == SOCKET_ERROR) { printf("Failed listen()\n"); return 0; } //循环接受客户的连接请求 sockaddr_in remoteAddr; int nAddrLen = sizeof(remoteAddr); printf("Length of sockaddr_in is: %d",nAddrLen); SOCKET sClient; char szText[] = "TCP Server Demo!\r\n"; while(TRUE) { sClient = ::accept(sListen,(SOCKADDR *)&remoteAddr,&nAddrLen); if (sClient == INVALID_SOCKET) { printf("Failed accapt()"); continue; } printf("接受到一个连接:%s\r\n",inet_ntoa(remoteAddr.sin_addr)); //向客户端发送数据 ::send(sClient,szText,strlen(szText),0); } //关闭客户端的连接 ::closesocket(sListen); return 0; } //TCPClient #include <stdio.h> #include "InitSock.h" CInitSock initSock; int main() { //创建套接字 SOCKET s = ::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (s == INVALID_SOCKET) { printf("Failed socket()\n"); return 0; } //在这里可以bind一个本地地址 //否则系统会自动安排 //填写远程地址信息 sockaddr_in servAddr; servAddr.sin_family = AF_INET; servAddr.sin_port = htons(4567); //注意,这里要填写服务器程序(TCPServer程序)所在机器的IP地址 //如果计算机没有联网,直接使用127.0.0.1即可 servAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); if (connect(s,(sockaddr *)&servAddr,sizeof(servAddr)) == -1) { printf("Failed connect()\n"); return 0; } //接收数据 char buff[256]; int nRev = ::recv(s,buff,256,0); if (nRev>0) { buff[nRev] = '\0'; printf("接受到数据:%s",buff); } //向服务端发送数据 char szText[] = "TCP client demo \r\n"; ::send(s,szText,strlen(szText),0); //关闭套接字 ::closesocket(s); return 0; }
window socket的简单例子
最新推荐文章于 2023-01-11 08:43:47 发布