#include<iostream>#include<winsock2.h>#include<ws2tcpip.h>usingnamespace std;// Need to link with Ws2_32.lib#pragmacomment(lib,"ws2_32.lib")intmain(){
cout <<"-----Server-----"<< endl;//1、加载库
WORD wVersionRequested;
WSADATA wsaData;int err;/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
wVersionRequested =MAKEWORD(2,2);
err =WSAStartup(wVersionRequested,&wsaData);if(err !=0){/* Tell the user that we could not find a usable *//* Winsock DLL. */printf("WSAStartup failed with error: %d\n", err);return1;}/* Confirm that the WinSock DLL supports 2.2.*//* Note that if the DLL supports versions greater *//* than 2.2 in addition to 2.2, it will still return *//* 2.2 in wVersion since that is the version we *//* requested. */if(LOBYTE(wsaData.wVersion)!=2||HIBYTE(wsaData.wVersion)!=2){/* Tell the user that we could not find a usable *//* WinSock DLL. */printf("Could not find a usable version of Winsock.dll\n");WSACleanup();return1;}elseprintf("The Winsock 2.2 dll was found okay\n");/* The Winsock DLL is acceptable. Proceed to use it. *//* Add network programming using Winsock here *//* then call WSACleanup when done using the Winsock dll *///2、创建套接字
SOCKET soc=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if(INVALID_SOCKET==soc){
cout <<" "<<WSAGetLastError()<< endl;WSACleanup();return1;}else{
cout <<"socket success"<< endl;}//3、绑定ip地址
sockaddr_in addrServer;
addrServer.sin_family = AF_INET;
addrServer.sin_port =htons(54321);
addrServer.sin_addr.S_un.S_addr = INADDR_ANY;
err =bind(soc,(sockaddr*)&addrServer,sizeof(addrServer));if(SOCKET_ERROR == err){
cout <<"bind error: "<<WSAGetLastError()<< endl;closesocket(soc);//关闭套接字WSACleanup();//上面已经加载库成功,所以需要卸载库return1;}else{
cout <<"bind success"<< endl;}//4、监听
err =listen(soc,10);if(SOCKET_ERROR == err){
cout <<"listen error: "<<WSAGetLastError()<< endl;closesocket(soc);//关闭套接字WSACleanup();//上面已经加载库成功,所以需要卸载库return1;}else{
cout <<"listen success"<< endl;}
sockaddr_in addrClient;int addrClientSize =sizeof(addrClient);char recvBuff[1024]="";char sendBuff[1024]="";int nRecvNum =0;int nSendNum =0;while(1){//循环接受连接//5、接受连接
SOCKET socClient =accept(soc,(sockaddr*)&addrClient,&addrClientSize);
cout <<"accept success"<<inet_ntoa(addrClient.sin_addr)<< endl;while(1){//和当前已经连接的客户端,循环收发数据//6、接收数据
nRecvNum=recv(socClient,recvBuff,sizeof(recvBuff),0);if(nRecvNum>0){
cout <<"client say: "<< recvBuff << endl;}elseif(nRecvNum==0){
cout <<"connet close "<< endl;break;}else{
cout <<"recv error"<<WSAGetLastError()<< endl;break;}//7、发送数据gets_s(sendBuff);
nSendNum =send(socClient,sendBuff,sizeof(sendBuff),0);if(SOCKET_ERROR == nSendNum){
cout <<"send error"<<WSAGetLastError()<< endl;break;}}//8、关闭与当前客户端链接使用的套接字closesocket(socClient);}//9、关闭套接字、卸载库closesocket(soc);WSACleanup();return0;}