Socket代码实现服务端 和 客户端之间通信
生活随笔
收集整理的這篇文章主要介紹了
Socket代码实现服务端 和 客户端之间通信
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
服務(wù)端代碼
// Socket_connection.cpp : 此文件包含 "main" 函數(shù)。程序執(zhí)行將在此處開始并結(jié)束。 // #ifndef UNICODE #define UNICODE #endif#define WIN32_LEAN_AND_MEAN#include <winsock2.h> #include <Ws2tcpip.h> #include <stdio.h> #include <iostream>#define DEFAULT_BUFLEN 512 // Link with ws2_32.lib #pragma comment(lib, "Ws2_32.lib")using namespace std;void main() {//Initialze winsockWSADATA wsaData;if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0){std::cout << "Can't Initialize winsock!Quiting!" << std::endl;;return;}//Creste a sockrtSOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0);if (sockSrv == INVALID_SOCKET) {wprintf(L"Can't create a socket with error %d\n", WSAGetLastError());WSACleanup();return;}//Bind the socket to an ip address and portint port = 5099;SOCKADDR_IN addrSrv;addrSrv.sin_family = AF_INET;addrSrv.sin_port = htons(port); //1024以上的端口號(hào)addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//Bind the socketint retVal = bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));if (retVal == SOCKET_ERROR) {printf("Failed bind:%d\n", WSAGetLastError());closesocket(sockSrv);WSACleanup();return;}else {std::cout << "Bind returned success" << std::endl;}//Tell winsock the socket is for listeningif (listen(sockSrv, SOMAXCONN) == SOCKET_ERROR) {printf("Listen failed:%d", WSAGetLastError());return;}//wait for a connectionSOCKADDR_IN addrClient;int clientSize = sizeof(addrClient);SOCKET sockConn = accept(sockSrv, (SOCKADDR*)&addrClient, &clientSize);if (sockConn == SOCKET_ERROR) {wprintf(L"accept failed with error: %ld\n", WSAGetLastError());closesocket(sockSrv);WSACleanup();return;}char host[NI_MAXHOST]; //Client's remote namechar service[NI_MAXSERV]; //Service (i.e. port)the client is connect onZeroMemory(host, NI_MAXHOST);//Same as memset(host,0,NI_MAXHOST)ZeroMemory(service, NI_MAXSERV);if (getnameinfo((sockaddr*)&addrClient, sizeof(addrClient), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0) {std::cout << "connect on port " << service << std::endl;}else {inet_ntop(AF_INET, &addrClient.sin_addr, host, NI_MAXHOST);std::cout << host << " connect on port " << ntohs(addrClient.sin_port) << std::endl;}//while loop:accept and echo message back to clientchar recvbuf[DEFAULT_BUFLEN] = "";int recvbuflen = DEFAULT_BUFLEN;memset(recvbuf, 0, sizeof(recvbuf));char sendbuf[] = "Client: sending data test\n";retVal = send(sockConn, sendbuf, sizeof(sendbuf), 0);if (retVal == SOCKET_ERROR) {wprintf(L"send failed with error: %d\n", WSAGetLastError());closesocket(sockSrv);WSACleanup();return;}do {retVal = recv(sockConn, recvbuf, recvbuflen, 0);if (retVal > 0) {wprintf(L"Bytes received: %d\n", retVal);printf("%s\n", recvbuf);}else if (retVal == 0)wprintf(L"Connection closed\n");elsewprintf(L"recv failed with error: %d\n", WSAGetLastError());} while (retVal > 0);closesocket(sockConn);//close socketclosesocket(sockSrv);//close winsockWSACleanup();system("pause"); }// 運(yùn)行程序: Ctrl + F5 或調(diào)試 >“開始執(zhí)行(不調(diào)試)”菜單 // 調(diào)試程序: F5 或調(diào)試 >“開始調(diào)試”菜單// 入門使用技巧: // 1. 使用解決方案資源管理器窗口添加/管理文件 // 2. 使用團(tuán)隊(duì)資源管理器窗口連接到源代碼管理 // 3. 使用輸出窗口查看生成輸出和其他消息 // 4. 使用錯(cuò)誤列表窗口查看錯(cuò)誤 // 5. 轉(zhuǎn)到“項(xiàng)目”>“添加新項(xiàng)”以創(chuàng)建新的代碼文件,或轉(zhuǎn)到“項(xiàng)目”>“添加現(xiàn)有項(xiàng)”以將現(xiàn)有代碼文件添加到項(xiàng)目 // 6. 將來,若要再次打開此項(xiàng)目,請(qǐng)轉(zhuǎn)到“文件”>“打開”>“項(xiàng)目”并選擇 .sln 文件客戶端代碼
// socket_client.cpp : 此文件包含 "main" 函數(shù)。程序執(zhí)行將在此處開始并結(jié)束。 // #ifndef UNICODE #define UNICODE #endif#define WIN32_LEAN_AND_MEAN#include <winsock2.h> #include <Ws2tcpip.h> #include <stdio.h> #include <iostream> #include <string>// Link with ws2_32.lib #pragma comment(lib, "Ws2_32.lib")using namespace std;void main() {//Initialze winsockWSADATA wsaData;if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0){std::cout << "Can't Initialize winsock!Quiting!" << std::endl;;return;}//Creste a sockrtSOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);if (sockClient == INVALID_SOCKET) {wprintf(L"Can't create a socket with error %d\n", WSAGetLastError());WSACleanup();return;}//Bind the socket to an ip address and portint port = 5099;SOCKADDR_IN addrSrv;addrSrv.sin_family = AF_INET;addrSrv.sin_port = htons(5099);//addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");inet_pton(AF_INET, "127.0.0.1",&addrSrv.sin_addr.S_un.S_addr);char buff[1024];memset(buff, 0, sizeof(buff));//向服務(wù)器發(fā)出連接請(qǐng)求if (connect(sockClient, (struct sockaddr*) & addrSrv, sizeof(addrSrv)) == INVALID_SOCKET) {printf("Connect failed:%d", WSAGetLastError());return;}else{//接收數(shù)據(jù)recv(sockClient, buff, sizeof(buff), 0);printf("%s\n", buff);}//發(fā)送數(shù)據(jù)//const char* buffSend = "hello, this is a Client....";//send(sockClient, buffSend, strlen(buffSend) + 1, 0);char sendbuf[BUFSIZ];std::cout << "Use quit to exit!\n";while (true) {std::cout << "Please input a string to send:";std::string str;getline(std::cin, str);if (str == "quit") {break;}ZeroMemory(sendbuf, BUFSIZ);strcpy_s(sendbuf, str.c_str());if (send(sockClient, sendbuf, strlen(sendbuf) + 1, 0) == SOCKET_ERROR) {wprintf(L"send failed with error: %d\n", WSAGetLastError());closesocket(sockClient);WSACleanup();break;}}//printf("%d", strlen(buffSend) + 1);//關(guān)閉套接字closesocket(sockClient);WSACleanup();system("pause"); }// 運(yùn)行程序: Ctrl + F5 或調(diào)試 >“開始執(zhí)行(不調(diào)試)”菜單 // 調(diào)試程序: F5 或調(diào)試 >“開始調(diào)試”菜單// 入門使用技巧: // 1. 使用解決方案資源管理器窗口添加/管理文件 // 2. 使用團(tuán)隊(duì)資源管理器窗口連接到源代碼管理 // 3. 使用輸出窗口查看生成輸出和其他消息 // 4. 使用錯(cuò)誤列表窗口查看錯(cuò)誤 // 5. 轉(zhuǎn)到“項(xiàng)目”>“添加新項(xiàng)”以創(chuàng)建新的代碼文件,或轉(zhuǎn)到“項(xiàng)目”>“添加現(xiàn)有項(xiàng)”以將現(xiàn)有代碼文件添加到項(xiàng)目 // 6. 將來,若要再次打開此項(xiàng)目,請(qǐng)轉(zhuǎn)到“文件”>“打開”>“項(xiàng)目”并選擇 .sln 文件演示結(jié)果
- 服務(wù)端
- ?客戶端
參考鏈接
- inet_pton()和inet_ntop()函數(shù)詳解_夕小瑤的賣萌屋-CSDN博客_inet_pton
- Programming reference for the Win32 API - Win32 apps | Microsoft Docs? 查詢函數(shù)的具體內(nèi)容,適用于微軟函數(shù)接口
- 問題解決:無法解析的外部符號(hào) _imp_XXXXXXXXX - 程序員大本營
- 常用socket函數(shù)詳解_G_BrightBoy的專欄-CSDN博客_socket函數(shù)參數(shù)詳解
- windows socket編程實(shí)現(xiàn)兩臺(tái)電腦間的通信_(tái)key_z的博客-CSDN博客_socket通信兩臺(tái)電腦之間
- c++ 網(wǎng)絡(luò)編程(一)TCP/UDP windows/linux 下入門級(jí)socket通信 客戶端與服務(wù)端交互代碼 - aircraft - 博客園
- 使用VS2019創(chuàng)建項(xiàng)目,添加文件和庫地址_CHYabc123456hh的博客-CSDN博客_vs怎么添加庫文件
總結(jié)
以上是生活随笔為你收集整理的Socket代码实现服务端 和 客户端之间通信的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: select选中的值_selenium下
- 下一篇: 做期货如何开户,有以下五步