WinTcpSever.h
#pragma once
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include<iostream>
#include<string>
#include<winSock2.h>
#pragma comment(lib,"WS2_32.lib")
using namespace std;
class TcpSocket
{
private:
SOCKET _userSocket;
sockaddr_in _uAddr;
SOCKET _clientSocket;
sockaddr_in _cAddr;
int len;
public:
TcpSocket() :_userSocket(0), _clientSocket(0), _uAddr({ 0 }), _cAddr({ 0 }), len(0)
{
WSADATA date;
WORD w = MAKEWORD(2, 0);
if (WSAStartup(w, &date) != 0)
{
cout << "初始化套接字失败" << endl;
}
}
int Bind(int port)
{
_userSocket = socket(AF_INET, SOCK_STREAM, 0);
_uAddr.sin_family = AF_INET;
_uAddr.sin_port = htons(port);
_uAddr.sin_addr.S_un.S_addr = INADDR_ANY;
return bind(_userSocket, (const sockaddr*)&_uAddr, sizeof(_uAddr));
}
int Listen(int num)
{
return listen(_userSocket, num);
}
SOCKET Accept()
{
len = sizeof(_cAddr);
_clientSocket = accept(_userSocket,(sockaddr*)&_cAddr,&len);
return _clientSocket;
}
string GetAddress()
{
return inet_ntoa(_cAddr.sin_addr);
}
SOCKET SentMesage(string meg)
{
return send(_clientSocket, meg.c_str(), meg.size() + 1, 0);
}
~TcpSocket()
{
closesocket(_userSocket);
closesocket(_clientSocket);
WSACleanup();
}
};
WinTcpSever.cpp
#include"WinTcpSever.h"
int main()
{
TcpSocket sever;
sever.Bind(1500);
sever.Listen(5);
cout << "服务器启动" << endl;
while (1)
{
if (sever.Accept() != INVALID_SOCKET)
{
cout << sever.GetAddress() << "连接服务器" << endl;
sever.SentMesage("Hello Windows");
}
}
return 0;
}
WinTcpClient.h
#pragma once
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include<iostream>
#include<string>
#include<winSock2.h>
#pragma comment(lib,"WS2_32.lib")
using namespace std;
class TcpSocket
{
private:
SOCKET _userSocket;
sockaddr_in _uAddr;
public:
TcpSocket() :_userSocket(0), _uAddr({ 0 })
{
WSADATA date;
WORD w = MAKEWORD(2, 0);
if (WSAStartup(w, &date) != 0)
{
cout << "初始化套接字失败" << endl;
}
}
int Request(const string& ip, int port)
{
_userSocket = socket(AF_INET, SOCK_STREAM, 0);
_uAddr.sin_family = AF_INET;
_uAddr.sin_port = htons(port);
_uAddr.sin_addr.S_un.S_addr = inet_addr(ip.c_str());
return connect(_userSocket, (const sockaddr*)&_uAddr, sizeof(_uAddr));
}
string RecvDate(int ReadLen)
{
char* mess = new char[ReadLen];
memset(mess, 0, ReadLen);
recv(_userSocket, mess, ReadLen, 0);
string ret(mess);
delete[] mess;
return ret;
}
~TcpSocket()
{
closesocket(_userSocket);
WSACleanup();
}
};
WinTcpClient.cpp
#include"WinTcpClient.h"
int main()
{
TcpSocket client;
client.Request("127.0.0.1",1500);
cout << "客户启动" << endl;
cout << "sever:" << client.RecvDate(1024) << endl;
getchar();
}
本地测试
|