//網絡套接字編程實例,服務器端,TCP通信。 #include <WinSock2.h> #pragma comment(lib,"ws2_32.lib") #include <iostream> #include <windows.h> using namespace std; int main() { WSADATA wsaData; WSAStartup(MAKEWORD(2,2),&wsaData); //初始化版本 SOCKET sList = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //初始化socket if (sList == INVALID_SOCKET) //判斷socket是否建立成功 { cout << "socket error\n"; } else { cout << "socket success\n"; } sockaddr_in asd; //申明bind中addr參數,這是申明,一個結構體。 asd.sin_family = AF_INET; //設置結構體,必須是:AF_INET asd.sin_port = htons(1990); //指定TCP或UDP通信服務端口號,htons函數將主機無符號短整型轉換成網絡字節順序,1990是本地監聽的端口號。 asd.sin_addr.S_un.S_addr = INADDR_ANY; //INADDR_ANY表示所有可用地址 if (bind(sList, (LPSOCKADDR)&asd, sizeof(asd)) == SOCKET_ERROR) //綁定本地IP和端口 { cout << "bind error"; closesocket(sList); return 0; } if (listen(sList, 5) == SOCKET_ERROR) { cout << "listen error"; closesocket(sList); return 0; }//監聽,5為連接最數,注意listen只支持上面的SOCK_STREAM也就是TCP,UDP不用條用此函數。 // 循環接受客戶的連接請求 sockaddr_in remoteAddr; SOCKET sClient; int nAddrlen = sizeof(remoteAddr); char revData[255]; while (1) { // 接受一個新連接 sClient = accept(sList, (SOCKADDR*)&remoteAddr, &nAddrlen); //錯誤 if (sClient == INVALID_SOCKET) { cout << "accept error"; continue; } //打印出連接者的ip cout << " 接受到一個連接:" << inet_ntoa(remoteAddr.sin_addr)<<"\n"; int ret = recv(sClient, revData, 255, 0); if (ret > 0) { //為了防止打印出錯,把字符串結尾設成0x00 revData[ret] = 0x00; cout<<revData; } //發送給客戶端數據 char *buff = "握手,我是來自服務端的信息,TCP建立成功\n"; send(sClient, buff, strlen(buff), 0); closesocket(sClient); } closesocket(sList); system("pause"); return 0; }
//網絡套接字編程實例,客戶端。 #include <WinSock2.h> #pragma comment(lib,"ws2_32.lib") #include <iostream> #include <windows.h> #include <WS2tcpip.h> using namespace std; int main() { WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); //初始化版本 SOCKET sList = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //初始化socket if (sList == INVALID_SOCKET) //判斷socket是否建立成功 { cout << "socket error\n"; } else { cout << "socket success\n"; } sockaddr_in asd; //申明bind中addr參數,這是申明,一個結構體。 asd.sin_family = AF_INET; //設置結構體,必須是:AF_INET asd.sin_port = htons(1990); //指定TCP或UDP通信服務端口號,htons函數將主機無符號短整型轉換成網絡字節順序,1990是本地監聽的端口號。 asd.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //INADDR_ANY表示所有可用地址 if (connect(sList, (sockaddr*)&asd, sizeof(asd)) == SOCKET_ERROR) { cout<<"connect error\n"; closesocket(sList); return 0; } char *buff = "我是來自客戶端的信息"; int nAddrlen = sizeof(asd); char revData[255]; send(sList, buff, strlen(buff), 0); int ret = recv(sList, revData, 255, 0); if (ret > 0) { revData[ret] = 0x00; cout << revData; } closesocket(sList); WSACleanup(); system("pause"); return 0; }