服务器代码
#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()
{
// 启动Windows socket 2.x环境
WORD ver = MAKEWORD(2, 2);
WSADATA dat;
WSAStartup(ver, &dat);
//----------------
// --用Socket API建立简易TCP服务器
// 创建一个socket
SOCKET _sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// 绑定用于接受客户端连接的网络端口
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(9527);
_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;
// 向客户端发送一条数据
char msgBuf[] = "Hello, I'm Server.";
while (true) {
_cSock = accept(_sock, (sockaddr*)&clientAddr, &nAddrLen);
if (INVALID_SOCKET == _cSock)
printf("接受到无效客户端SOCKET...\n");
printf("新客户端加入:IP = %s\n", inet_ntoa(clientAddr.sin_addr));
send(_cSock, msgBuf, sizeof(msgBuf), 0);
}
closesocket(_sock);
WSACleanup();
return 0;
}
客户端代码
#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()
{
// 启动Windows socket 2.x环境
WORD ver = MAKEWORD(2, 2);
WSADATA dat;
WSAStartup(ver, &dat);
//----------------
// 建立一个socket
SOCKET _sock = socket(AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == _sock)
printf("创建套接字错误...\n");
// 连接服务器 connect
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(9527);
_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("连接Socket成功...\n");
// 接受服务器信息
char recvBuf[256] = {};
int nlen = recv(_sock, recvBuf, 256, 0);
if (nlen > 0)
printf("接受到数据:%s\n", recvBuf);
// 关闭套接字
closesocket(_sock);
WSACleanup();
return 0;
}