#define WIN32_LEAN_AND_MEAN
#include<windows.h>
#include<WinSock2.h>
#include<stdio.h>
#pragma comment(lib,"ws2_32.lib")
int main()
{
//启动windows socket 2.x 环境
WORD ver = MAKEWORD(2, 2);
WSADATA dat;
WSAStartup(ver, &dat);
//-----用Scoket API建立简易TCP客户端
//1、建立一个SCOKET
SOCKET _sock = socket(AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == _sock)
{
printf("错误,建立SOCKET失败... \n");
}
else
{
printf("建立socket成功... \n");
}
//2、连接服务器connect
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");
}
//3、接收服务器信息 recv
char recvBuf[256] = {};
int nlen = recv(_sock, recvBuf, 256, 0);
if (nlen > 0)
{
printf("接收到数据:%s",recvBuf);
}
//4、关闭socket套接字
closesocket(_sock);
//清除windows socket环境
WSACleanup();
getchar();
return 0;
}