调用Windows下的接口必须先进行初始化,比如:
WORD ver = MAKEWORD(2,2); WSADATA dat; WSAStartup(ver,&dat); //-------------------------------- //这里面的代码和Linux差不多 //-------------------------------- WSACleanup();
服务器:
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <windows.h>
#include <WinSock2.h>
#include <stdio.h>
int main()
{
WORD ver = MAKEWORD(2,2);
WSADATA dat;
WSAStartup(ver,&dat);
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("ERROR,绑定用于接受客户端连接的网络端口失败...\n");
}
else
{
printf("绑定成功...\n");
}
if (SOCKET_ERROR == listen(_sock, 5))
{
printf("错误,监听网络端口失败...\n");
}
else
{
printf("监听网络端口成功...\n");
}
sockaddr_in clientAddr = {};
int nAddrLen = sizeof(sockaddr_in);
SOCKET _cSock = INVALID_SOCKET;
_cSock = accept(_sock, (sockaddr*)&clientAddr, &nAddrLen);
if (INVALID_SOCKET == _cSock)
{
printf("错误,接收到无效客户端SOCKET...\n");
}
printf("新客户端加入:socket = %d IP = %s \n", (int)_cSock,inet_ntoa(clientAddr.sin_addr));
char _recvBuf[128] = {};
while (true)
{
int nLen = recv(_cSock, _recvBuf, 128, 0);
if(nLen <= 0)
{
printf("客户端已退出,任务结束。");
break;
}
printf("收到命令:%s \n",_recvBuf);
if (0 == strcmp(_recvBuf,"getName"))
{
char msgBuf[] = "Dragon";
send(_cSock,msgBuf,strlen(msgBuf)+1,0);
}
else if (0 == strcmp(_recvBuf, "getAge"))
{
char msgBuf[] = "21";
send(_cSock, msgBuf, strlen(msgBuf) + 1, 0);
}
else
{
char msgBuf[] = "???";
send(_cSock, msgBuf, strlen(msgBuf) + 1, 0);
}
}
closesocket(_sock);
WSACleanup();
printf("任务结束,退出");
getchar();
return 0;
}
客户端:
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <WinSock2.h>
#include <stdio.h>
int main()
{
WORD ver = MAKEWORD(2, 2);
WSADATA dat;
WSAStartup(ver, &dat);
SOCKET _sock = socket(AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == _sock)
{
printf("错误,建立Socket失败...\n");
}
else
{
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("连接服务器失败...\n");
}
else
{
printf("连接服务器成功...\n");
}
while (true)
{
char cmdBuf[128] = {};
scanf("%s",cmdBuf);
if (0 == strcmp(cmdBuf, "exit"))
{
printf("收到exit,任务结束");
break;
}
else
{
send(_sock, cmdBuf, strlen(cmdBuf) + 1, 0);
}
char recvBuf[128] = {};
int nlen = recv(_sock, recvBuf, 128, 0);
if (nlen > 0)
{
printf("接受到的数据:%s \n", recvBuf);
}
}
closesocket(_sock);
WSACleanup();
printf("已退出");
getchar();
return 0;
}
测试:
|