//Windows.h 包含旧版本 socket 的 一些宏定义 因此: Winsock2.h 要包含在 Windows.h 前面 //方法一
//方法二: 第一行 定义 :#define WIN32_LEAN_AND_MEAN 避免 宏定义冲突;
#define WIN32_LEAN_AND_MEAN // 引用此红 会尽量避免 引用比较早期的 (会引起冲突的一些库);
#include <Windows.h>
#include <Winsock2.h>
#include <stdio.h>
using namespace std;
#pragma comment(lib,"ws2_32.lib")//方法二 工程里面添加 lib;
//Server
int main()
{
WORD Ver = MAKEWORD(2, 2);
WSADATA data;
WSAStartup(Ver, &data);//启动sock 网络环境
///
//--用socket API 建立建议TCP服务端
// 1 建立一个socket//套接字
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// 2 bind 绑定用于接收客户端连接的网络端口
sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(8888);//host to net unsigned short
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");// INADDR_ANY;//inet_addr("127.0.0.1");127 内网
if (SOCKET_ERROR == bind(sock, (sockaddr *)&addr, sizeof(sockaddr)))
{
printf("Error ,绑定用于接收客户端连接的网络端口失败... \r\n");
}
else
{
printf("绑定网络端口成功... \r\n");
}
// 3 listen 监听网络端口
if (SOCKET_ERROR == listen(sock, 5))//等待有多少人进行连接;
{
printf("Error ,监听网络端口失败... \r\n");
}
else
{
printf("监听网络端口成功... \r\n");
}
// 4 accept 等待接受客户端连接
sockaddr_in client;
int nAddrLen = sizeof(sockaddr_in);
SOCKET sock_Client = INVALID_SOCKET;
char msgBuff[] = "hello, I‘m Server.";
while (true)
{
sock_Client = accept(sock, (sockaddr *)&client, &nAddrLen);
if (INVALID_SOCKET == sock_Client)
{
printf("Error, 接受到无效客户端SOCKET... \r\n");
}
printf("接收 客户端sock = %d 客户端 IP = %s,客户端端口 = %d", sock_Client, inet_ntoa(client.sin_addr), client.sin_port);
// 5 Send 向客户端发送一条数据
send(sock_Client, msgBuff, strlen(msgBuff) + 1, 0);
}
// 6 关闭套接字Colsesocket;
closesocket(sock);
////
WSACleanup(); //关闭 sock 网络环境
return 0;
}
//Client
int main()
{
WORD Ver = MAKEWORD(2, 2);
WSADATA data;
WSAStartup(Ver, &data);//启动sock 网络环境
///
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8888);
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (SOCKET_ERROR == connect(sock, (sockaddr *)&addr, sizeof(sockaddr)))
{
printf("客户端: 连接服务器失败... \r\n");
return 0;
}
else
{
printf("客户端: 连接服务器成功... \r\n");
}
char DataBuff[1024] = { 0 };
char ScanfBuff[50] = { 0 };
while (true)
{
int nLen = recv(sock, DataBuff, sizeof(DataBuff), 0);
if (nLen > 0)
{
printf("接收的数据: %s... \r\n", DataBuff);
}
}
////
WSACleanup(); //关闭 sock 网络环境
return 0;
}