功能:向服务器端发送一个字符串,属于最简易的形式,一共需要4个主要步骤,初始化-建立套接字-连接服务器-发送数据

winSockets编程(三)最简单的C/S形式-LMLPHP

/************************************************************************
*  此代码为最简易的客户端形式,需要背诵
*   作者: Tinaluo
*  日期: 2017/10/24
************************************************************************/ #include <WinSock2.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib") int main()
{
WSADATA wsd;
if (WSAStartup(MAKEWORD(, ), &wsd) != )
{
std::cout << "版本不支持" << std::endl;
return -;
} SOCKET sHost = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == sHost)
{
std::cout << "创建套接字失败" << std::endl;
WSACleanup();
return -;
} SOCKADDR_IN servAddr;
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servAddr.sin_port = htons();
int retVal = connect(sHost, (LPSOCKADDR)&servAddr, sizeof(servAddr));
if (retVal == SOCKET_ERROR)
{
std::cout << "连接服务器失败!" << std::endl;
closesocket(sHost);
WSACleanup();
return -;
} char buf[MAX_PATH];
ZeroMemory(buf, MAX_PATH);
strcpy_s(buf, "Connect successful!");
retVal = send(sHost, buf, strlen(buf), );
if (retVal == SOCKET_ERROR)
{
std::cout << "发送失败!" << std::endl;
closesocket(sHost);
WSACleanup();
return -;
} std::cout << "关闭套接字!" << std::endl;
closesocket(sHost);
WSACleanup();
return ;
}

服务端

/************************************************************************
* 最简易服务器端
* 目标:接收客户端问候(此程序需要极其熟练并背诵!)
* 作者:Luotian
* 日期:2017/10/25
************************************************************************/
#include <iostream>
#include "winsock2.h"
#pragma comment(lib, "ws2_32.lib") int main()
{
WSADATA wsd;
if (WSAStartup(MAKEWORD(, ), &wsd) != )
{
std::cout << "初始化失败!" << std::endl;
return -;
} SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == serverSocket)
{
std::cout << "创建套接字失败!" << std::endl;
WSACleanup();
return -;
} SOCKADDR_IN addrServ;
addrServ.sin_family = AF_INET;
addrServ.sin_port = htons();
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 -;
} retVal = listen(serverSocket, );
if (SOCKET_ERROR == retVal)
{
std::cout << "创建监听失败!" << std::endl;
closesocket(serverSocket);
WSACleanup();
return -;
} 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 -;
} char buf[MAX_PATH];
ZeroMemory(buf, MAX_PATH);
retVal = recv(clientSocket, buf, MAX_PATH, );
if (SOCKET_ERROR == retVal)
{
std::cout << "获取数据失败!" << std::endl;
closesocket(serverSocket);
closesocket(clientSocket);
WSACleanup();
return -;
}
std::cout <<buf<< std::endl; closesocket(serverSocket);
closesocket(clientSocket);
WSACleanup();
return ;
}
05-11 19:20