服务端
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include<Windows.h>
#include<WinSock2.h>
#include<stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WORD ver = MAKEWORD(2, 2);
WSAData data;
int statut = WSAStartup(ver, &data);
SOCKET _sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(4567);
_sin.sin_addr.S_un.S_addr = INADDR_ANY;
if (SOCKET_ERROR == bind(_sock, (sockaddr*)&_sin, sizeof(_sin)))
{
printf("bind绑定失败...\n");
}
else
{
printf("bind绑定成功!\n");
}
if (SOCKET_ERROR == listen(_sock, 5))
{
printf("listen失败...\n");
}
else
{
printf("listen成功...\n");
}
sockaddr_in clientAddr = {};
int addrlen = sizeof(sockaddr);
SOCKET _cSock = INVALID_SOCKET;
const char * msgBuf = "hello,server!";
_cSock = accept(_sock, (sockaddr*)&clientAddr, &addrlen);
if (INVALID_SOCKET == _cSock)
{
printf("接收到无效客户端SOCKET...\n");
}
printf("新客户端加入 IP: %s \n", inet_ntoa(clientAddr.sin_addr));
char _recvBuf[128] = {};
while (true)
{
int nLen = recv(_cSock, _recvBuf, 128, 0);
if (nLen <= 0)
{
printf("新客户端已退出...,任务结束.");
break;
}
if (0 == strcmp(_recvBuf, "getName"))
{
msgBuf = "moddemod";
}
else if (0 == strcmp(_recvBuf, "getAge"))
{
msgBuf = "18";
}
else
{
msgBuf = "I can't understand your means....\n";
}
int msgBufLen = strlen(msgBuf);
send(_cSock, msgBuf, msgBufLen + 1, 0);
}
closesocket(_sock);
WSACleanup();
return 0;
}
客户端
#define WIN32_LEAN_AND_MEAN
#include<Windows.h>
#include<WinSock2.h>
#include<stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WORD ver = MAKEWORD(2, 2);
WSADATA data;
WSAStartup(ver, &data);
SOCKET _sock = socket(AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == _sock)
{
printf("socket创建失败...\n");
}
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(4567);
_sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
int ret = connect(_sock, (sockaddr*)&_sin, sizeof(sockaddr_in));
if (SOCKET_ERROR == ret)
{
printf("connect连接失败...\n");
}
else
{
printf("connect连接成功...\n");
}
char cmdBuf[128] = {};
while (true)
{
memset(cmdBuf, 0, 128);
scanf("%s", cmdBuf);
if (0 == strcmp(cmdBuf, "exit"))
{
break;
}
else
{
send(_sock, cmdBuf, strlen(cmdBuf) + 1, 0);
}
char recvBuf[256] = {};
int nLen = recv(_sock, recvBuf, 256, 0);
if (nLen > 0)
{
printf("recv: %s\n", recvBuf);
}
}
closesocket(_sock);
WSACleanup();
return 0;
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200314160214401.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzgzMzY0Mg==,size_16,color_FFFFFF,t_70)