服务端代码
// Socket_connection.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#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以上的端口号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");
}// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
客户端代码
// socket_client.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#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));//向服务器发出连接请求if (connect(sockClient, (struct sockaddr*) & addrSrv, sizeof(addrSrv)) == INVALID_SOCKET) {printf("Connect failed:%d", WSAGetLastError());return;}else{//接收数据recv(sockClient, buff, sizeof(buff), 0);printf("%s\n", buff);}//发送数据//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);//关闭套接字closesocket(sockClient);WSACleanup();system("pause");
}// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
演示结果
参考链接
- inet_pton()和inet_ntop()函数详解_夕小瑶的卖萌屋-CSDN博客_inet_pton
- Programming reference for the Win32 API - Win32 apps | Microsoft Docs 查询函数的具体内容,适用于微软函数接口
- 问题解决:无法解析的外部符号 _imp_XXXXXXXXX - 程序员大本营
- 常用socket函数详解_G_BrightBoy的专栏-CSDN博客_socket函数参数详解
- windows socket编程实现两台电脑间的通信_key_z的博客-CSDN博客_socket通信两台电脑之间
- c++ 网络编程(一)TCP/UDP windows/linux 下入门级socket通信 客户端与服务端交互代码 - aircraft - 博客园
- 使用VS2019创建项目,添加文件和库地址_CHYabc123456hh的博客-CSDN博客_vs怎么添加库文件