二:简单的C/S阻塞模型
SOCKET socket(int af, int type, int protocol);
参数
返回值
int bind(SOCKET s, const struct sockaddr* addr, int namelen);
参数
返回值
sockaddr结构体
1 struct sockaddr { 2 u_short sa_family; 3 char sa_data[14]; 4 };
1 struct sockaddr_in { 2 short sin_family; //地址类型,同socket()函数第一个参数 3 USHORT sin_port; //端口号 4 IN_ADDR sin_addr; //IP地址 5 CHAR sin_zero[8]; //占位符,预留给系统使用 6 };
1 //192.168.1.120 2 struct in_addr { 3 union { 4 struct { 5 UCHAR s_b1; //192 6 UCHAR s_b2; //168 7 UCHAR s_b3; //1 8 UCHAR s_b4; //120 9 } S_un_b; 10 11 struct { 12 USHORT s_w1; //高8位=168,低8位=192 13 USHORT s_w2; //高8位=120,低8位=1 14 } S_un_w; 15 16 ULONG S_addr; //可以用inet_addr函数构造地址 17 } S_un; 18 19 #define s_addr S_un.S_addr /* can be used for most tcp & ip code */ 20 #define s_host S_un.S_un_b.s_b2 // host on imp 21 #define s_net S_un.S_un_b.s_b1 // network 22 #define s_imp S_un.S_un_w.s_w2 // imp 23 #define s_impno S_un.S_un_b.s_b4 // imp # 24 #define s_lh S_un.S_un_b.s_b3 // logical host 25 };
1 { 2 sockaddr_in si; 3 si.sin_family = AF_INET; 4 si.sin_addr.s_addr = inet_addr("127.0.0.1"); 5 si.sin_port = htons(12345); 6 bind(socketServer, reinterpret_cast<sockaddr*>(&si), sizeof(si)); 7 }
int listen(SOCKET s, int backlog);
参数
返回值
SOCKET accept(SOCKET s, struct sockaddr* addr, int* addrlen);
参数
返回值
int recv(SOCKET s, char *buf, int len, int flags);
参数
返回值
int send(SOCKET s, const char* buf, int len, int flags);
参数
返回值
int closesocket (SOCKET s);
参数
返回值
1 #define _WINSOCK_DEPRECATED_NO_WARNINGS 2 3 #include <iostream> 4 #include <WinSock2.h> 5 #pragma comment(lib,"ws2_32.lib") 6 using namespace std; 7 8 const int nMajorVersion = 2; 9 const int nMinorVersion = 2; 10 11 int main() 12 { 13 WORD dwVersion = MAKEWORD(nMajorVersion, nMinorVersion); 14 WSADATA data; 15 int nRet = WSAStartup(dwVersion, &data); 16 if (nRet != 0) 17 { 18 cout << "start network libary error!" << endl; 19 return 0; 20 } 21 22 if (nMajorVersion != LOBYTE(data.wVersion) || nMinorVersion != HIBYTE(data.wVersion)) 23 { 24 cout << "version error" << endl; 25 WSACleanup(); 26 return 0; 27 } 28 29 SOCKET socketServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 30 if (INVALID_SOCKET == socketServer) 31 { 32 cout << "create socket error, error code = %d" << WSAGetLastError() << endl; 33 WSACleanup(); 34 return 0; 35 } 36 37 sockaddr_in si; 38 si.sin_family = AF_INET; 39 si.sin_addr.s_addr = inet_addr("127.0.0.1"); 40 si.sin_port = htons(12345); 41 nRet = bind(socketServer, reinterpret_cast<sockaddr*>(&si), sizeof(si)); 42 if (nRet == SOCKET_ERROR) 43 { 44 int nCode = WSAGetLastError(); 45 cout << "bind error! code = " << nCode << endl; 46 closesocket(socketServer); 47 WSACleanup(); 48 return 0; 49 } 50 51 nRet = listen(socketServer, SOMAXCONN); 52 if (nRet == SOCKET_ERROR) 53 { 54 int nCode = WSAGetLastError(); 55 cout << "bind error! code = " << nCode << endl; 56 closesocket(socketServer); 57 WSACleanup(); 58 return 0; 59 } 60 61 while (1) 62 { 63 sockaddr_in siClient; 64 int nLen = sizeof(siClient); 65 SOCKET socketClient = accept(socketServer, reinterpret_cast<sockaddr*>(&siClient), &nLen); 66 if (socketClient == INVALID_SOCKET) 67 { 68 cout << "accept Error, Code = " << WSAGetLastError() << endl; 69 continue; 70 } 71 else 72 { 73 cout << "Has Connect SocketID = " << (int)socketClient << endl; 74 } 75 76 while (1) 77 { 78 char buf[1024] = { 0 }; 79 nRet = recv(socketClient, buf, 1024, 0); 80 if (nRet == 0) 81 { 82 cout << "Client Disconnect!" << endl; 83 closesocket(socketClient); 84 break; 85 } 86 else if (nRet == SOCKET_ERROR) 87 { 88 cout << "Receive Client Data Error, Code = " << WSAGetLastError() << endl; 89 closesocket(socketClient); 90 break; 91 } 92 else 93 { 94 cout << "Client : " << buf << endl; 95 96 std::string str; 97 cin >> str; 98 int nSned = send(socketClient, str.c_str(), str.length(), 0); 99 if (nSned == 0) 100 { 101 cout << "Client Disconnect!" << endl; 102 closesocket(socketClient); 103 break; 104 } 105 else if (nSned > 0 && nSned < str.length()) 106 { 107 cout << "send partial data, length = " << nSned << endl; 108 } 109 else if (nSned == SOCKET_ERROR) 110 { 111 cout << "send error, code = " << WSAGetLastError() << endl; 112 closesocket(socketClient); 113 break; 114 } 115 } 116 } 117 118 } 119 120 closesocket(socketServer); 121 WSACleanup(); 122 return 0; 123 }
- 连接服务器
- 与服务器收发数据
int connect(SOCKET s, const struct sockaddr* name, int namelen);
参数
返回值
1 #define _CRT_SECURE_NO_WARNINGS 2 #define _WINSOCK_DEPRECATED_NO_WARNINGS 3 4 #include <iostream> 5 #include <WinSock2.h> 6 #include <string> 7 8 #pragma comment(lib, "ws2_32.lib") 9 10 using namespace std; 11 12 const unsigned int marjorVersion = 2; 13 const unsigned int minorVersion = 2; 14 15 SOCKET ServerSocket; 16 17 BOOL WINAPI func(DWORD CtrlType) 18 { 19 if(CtrlType == CTRL_CLOSE_EVENT) 20 { 21 if (ServerSocket != INVALID_SOCKET) 22 { 23 closesocket(ServerSocket); 24 ServerSocket = INVALID_SOCKET; 25 } 26 WSACleanup(); 27 } 28 return TRUE; 29 } 30 31 int main() 32 { 33 SetConsoleCtrlHandler(func, TRUE); //强制退出 自动关闭网络 34 35 WORD wVersion = MAKEWORD(marjorVersion, minorVersion); 36 WSAData SocketVersionInfo; 37 int nRet = WSAStartup(wVersion, &SocketVersionInfo); 38 if (nRet != 0) 39 { 40 cout << "启动套接字失败" << endl; 41 return 0; 42 } 43 44 ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 45 if (ServerSocket == INVALID_SOCKET) 46 { 47 int nErrorCode = WSAGetLastError(); 48 std::cout << "套接字创建失败,错误码 " << nErrorCode << std::endl; 49 WSACleanup(); 50 return 0; 51 } 52 53 sockaddr_in addressInfo; 54 addressInfo.sin_port = htons(12345); 55 addressInfo.sin_family = AF_INET; 56 addressInfo.sin_addr.s_addr = inet_addr("127.0.0.1"); 57 if (SOCKET_ERROR == connect(ServerSocket, reinterpret_cast<sockaddr*>(&addressInfo), sizeof(addressInfo))) 58 { 59 int nErrorCode = WSAGetLastError(); 60 std::cout << "连接服务器失败,错误码 " << nErrorCode << std::endl; 61 closesocket(ServerSocket); 62 ServerSocket = INVALID_SOCKET; 63 WSACleanup(); 64 return 0; 65 } 66 67 while (1) 68 { 69 string str; 70 cout << "输入要发送的数据:" << endl; 71 cin >> str; 72 int nSendSize = send(ServerSocket, str.c_str(), str.length(), 0); 73 if (nSendSize == SOCKET_ERROR) 74 { 75 int nErrorCode = WSAGetLastError(); 76 cout << "send error, error code " << nErrorCode << endl; 77 closesocket(ServerSocket); 78 ServerSocket = INVALID_SOCKET; 79 WSACleanup(); 80 return 0; 81 } 82 83 char buf[1024] = { 0 }; 84 int nAcceptSize = recv(ServerSocket, buf, 1000, 0); 85 if (nAcceptSize != 0) 86 cout << "客户端:" << buf << endl; 87 } 88 89 closesocket(ServerSocket); 90 ServerSocket = INVALID_SOCKET; 91 WSACleanup(); 92 return 0; 93 }