功能:向服务器端发送一个字符串,属于最简易的形式,一共需要4个主要步骤,初始化-建立套接字-连接服务器-发送数据
/************************************************************************* 此代码为最简易的客户端形式,需要背诵 * 作者: Tinaluo* 日期: 2017/10/24************************************************************************/#include#include #pragma comment(lib,"ws2_32.lib")int main(){ WSADATA wsd; if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) { std::cout << "版本不支持" << std::endl; return -1; } SOCKET sHost = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == sHost) { std::cout << "创建套接字失败" << std::endl; WSACleanup(); return -1; } SOCKADDR_IN servAddr; servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servAddr.sin_port = htons(8000); int retVal = connect(sHost, (LPSOCKADDR)&servAddr, sizeof(servAddr)); if (retVal == SOCKET_ERROR) { std::cout << "连接服务器失败!" << std::endl; closesocket(sHost); WSACleanup(); return -1; } char buf[MAX_PATH]; ZeroMemory(buf, MAX_PATH); strcpy_s(buf, "Connect successful!"); retVal = send(sHost, buf, strlen(buf), 0); if (retVal == SOCKET_ERROR) { std::cout << "发送失败!" << std::endl; closesocket(sHost); WSACleanup(); return -1; } std::cout << "关闭套接字!" << std::endl; closesocket(sHost); WSACleanup(); return 0;}
服务端
/************************************************************************* 最简易服务器端* 目标:接收客户端问候(此程序需要极其熟练并背诵!)* 作者:Luotian* 日期:2017/10/25************************************************************************/#include#include "winsock2.h"#pragma comment(lib, "ws2_32.lib")int main(){ WSADATA wsd; if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) { std::cout << "初始化失败!" << std::endl; return -1; } SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == serverSocket) { std::cout << "创建套接字失败!" << std::endl; WSACleanup(); return -1; } SOCKADDR_IN addrServ; addrServ.sin_family = AF_INET; addrServ.sin_port = htons(8000); addrServ.sin_addr.s_addr = INADDR_ANY; int retVal = bind(serverSocket, (LPSOCKADDR)&addrServ, sizeof(SOCKADDR_IN)); if (SOCKET_ERROR == retVal) { std::cout << " 绑定套接字失败!" << std::endl; closesocket(serverSocket); WSACleanup(); return -1; } retVal = listen(serverSocket, 1); if (SOCKET_ERROR == retVal) { std::cout << "创建监听失败!" << std::endl; closesocket(serverSocket); WSACleanup(); return -1; } sockaddr_in addrClient; int addrClientlen = sizeof(addrClient); SOCKET clientSocket = accept(serverSocket, (sockaddr FAR*)&addrClient, &addrClientlen); if (INVALID_SOCKET == clientSocket) { std::cout << "接受请求失败!" << std::endl; closesocket(serverSocket); WSACleanup(); return -1; } char buf[MAX_PATH]; ZeroMemory(buf, MAX_PATH); retVal = recv(clientSocket, buf, MAX_PATH, 0); if (SOCKET_ERROR == retVal) { std::cout << "获取数据失败!" << std::endl; closesocket(serverSocket); closesocket(clientSocket); WSACleanup(); return -1; } std::cout < << std::endl; closesocket(serverSocket); closesocket(clientSocket); WSACleanup(); return 0;}