用Socket API建立简易TCP客户端:
实现代码如下:
#include
#define WIN32_LEAN_AND_MEAN
#include
#include
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
WSADATA data;
WORD version = MAKEWORD(2, 2);
// 初始化Sokcet库
WSAStartup(version, &data);
//------------
//-- 用Socket API建立简易TCP客户端
// 1 建立一个socket
SOCKET _sock;
_sock = socket(AF_INET, SOCK_STREAM, 0); // 客户端的协议类型可以直接给0
if (INVALID_SOCKET == _sock)
{
cout << "client : create socket error !" << endl;
WSACleanup();
return -1;
}
else
{
cout << "client : create socket success !" << endl;
}
// 2 连接服务器 connect
sockaddr_in _sockaddr;
_sockaddr.sin_family = AF_INET;
_sockaddr.sin_port = htons(4567);
_sockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
int ret = connect(_sock, (sockaddr*)&_sockaddr, sizeof(sockaddr_in));
if (SOCKET_ERROR == ret)
{
cout << "client : connect error !" << endl;
WSACleanup();
return -1;
}
else
{
cout << "client : connect success !" << endl;
}
// 3 接收服务器信息 recv
char buffer[256] = { 0 };
int len = recv(_sock, buffer, sizeof(buffer), 0);
if (len > 0)
{
cout << "client : recv " << len << "byte : " << buffer << endl;
}
// 4 关闭套节字closesocket
closesocket(_sock);
// 对Socket资源进行处理
WSACleanup();
getchar();
return 0;
}
用Socket API建立简易TCP服务端:
实现代码如下:
#include
#define WIN32_LEAN_AND_MEAN
#include
#include
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
WSADATA data;
WORD version = MAKEWORD(2, 2);
// 初始化Sokcet库
WSAStartup(version, &data);
//-- 用Socket API建立简易TCP服务端
// 1 建立一个socket
SOCKET _sock;
_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == _sock)
{
cout << "server : create socket error !" << endl;
WSACleanup();
return -1;
}
else
{
cout << "server : create socket success !" << endl;
}
// 2 bind 绑定用于接受客户端连接的网络端口
sockaddr_in _sockaddr;
_sockaddr.sin_family = AF_INET;
_sockaddr.sin_port = htons(4567);
_sockaddr.sin_addr.S_un.S_addr = ADDR_ANY; //inet_addr("127.0.0.1");
int ret = bind(_sock, (sockaddr*)&_sockaddr, sizeof(sockaddr_in));
if (SOCKET_ERROR == ret)
{
cout << "server : bind error!" << endl;
WSACleanup();
return -1;
}
else
{
cout << "server : bind success !" << endl;
}
// 3 listen 监听网络端口
ret = listen(_sock, 5);
if (SOCKET_ERROR == ret)
{
cout << "server : listen error !" << endl;
WSACleanup();
return -1;
}
else
{
cout << "server : listen success !" << endl;
}
sockaddr_in _sockaddr_in;
int len = sizeof(sockaddr_in);
char buffer[] = "hello, client! I am server !";
while (true)
{
// 4 accept 等待接受客户端连接
SOCKET clientSock = accept(_sock, (sockaddr*)&_sockaddr_in, &len);
if (INVALID_SOCKET == clientSock)
{
cout << "server : accept bad socket!" << endl;
}
else
{
cout << "server : new client join, IP : " << inet_ntoa(_sockaddr_in.sin_addr) << endl;
}
// 5 send 向客户端发送一条数据
int sendLen = send(clientSock, buffer, sizeof(buffer), 0);
cout << "server : send " << sendLen << "bytes !" << endl;
}
// 6 关闭套节字closesocket
closesocket(_sock);
// 对Socket资源进行处理
WSACleanup();
getchar();
return 0;
}
参考资料: