WinSock基础编程基本步骤

//WinSock库的装入和退出类 #ifndef _InitWinSock_H_ #define _InitWinSock_H_ #pragma comment(lib,"wsock32") class CInitWinSock { public: CInitWinSock(BYTE minorVer=2,BYTE majorVer=2) { WSAData wsaData; WORD sockVersion = MAKEWORD(minorVer, majorVer); if(::WSAStartup(sockVersion,&wsaData)!=0) exit(0); } ~CInitWinSock() { ::WSACleanup(); } }; #endif

 

//创建WinSock,并初始化 SOCKET m_s; //创建WinSock m_s=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(m_s==INVALID_SOCKET) { AfxMessageBox(_T("winSock 创建失败!"),0,MB_OK); ::WSACleanup(); return; } //声明本地IP sockaddr_in sin; sin.sin_family=AF_INET;//The Internet Protocol version 4 (IPv4) address family. sin.sin_port=htons(8888); sin.sin_addr.S_un.S_addr=INADDR_ANY;//本机所有IP地址 if(::bind(m_s,(LPSOCKADDR)&sin,sizeof(sin))==SOCKET_ERROR) { AfxMessageBox(_T("绑定失败"),0,MB_OK); ::WSACleanup(); return; } if(::listen(m_s,2)==SOCKET_ERROR) { AfxMessageBox(_T("无法监听"),0,MB_OK); ::WSACleanup(); return; }

 

//这是客户端使用,连接服务端函数 if(::connect(m_s, (sockaddr*)&servAddr, sizeof(servAddr)) == -1) { AfxMessageBox(_T("Error"),0,MB_OK); return; } char buff[256]; //接收字符串 int nRecv = ::recv(m_s, buff, 256, 0); if(nRecv > 0) { buff[nRecv] = '/0'; str.Format(_T("%s"),(char *)buff); //AfxMessageBox(str,0,MB_OK); GetDlgItem(IDC_EDT_REC)->SetWindowText(str); }

//接受连接 Socket client=::accept(m_s,(SOCKADDR *)&remoteAddr,&nAddrLen); if(client==INVALID_SOCKET) { AfxMessageBox(_T("连接失败"),0,MB_OK); continue; } GetDlgItem(IDC_EDT_CON)->SetWindowText(_T("中国人")); ::send(client,szText,strlen(szText),0); ::closesocket(client);

你可能感兴趣的:(编程,Stream,socket,Class,byte,internet)