#pragma once
#include <list>
// 定义iMessageType的值
#define LOGIN 1
#define LOGOUT 2
#define P2PTRANS 3
#define GETALLUSER 4
// 服务器端口
#define SERVER_PORT 6060
// Client登录时向服务器发送的消息
struct stLoginMessage
{
char userName[10];
char password[10];
};
// Client注销时发送的消息
struct stLogoutMessage
{
char userName[10];
};
// Client向服务器请求另外一个Client(userName)向自己方向发送UDP打洞消息
struct stP2PTranslate
{
char userName[10];
};
// Client向服务器发送的消息格式
struct stMessage
{
int iMessageType;
union _message
{
stLoginMessage loginmember;
stLogoutMessage logoutmember;
stP2PTranslate translatemessage;
}message;
};
// 客户节点信息
struct stUserListNode
{
char userName[10];
unsigned int ip;
unsigned short port;
};
// Server向Client发送的消息
struct stServerToClient
{
int iMessageType;
union _message
{
stUserListNode user;
}message;
};
//======================================
// 下面的协议用于客户端之间的通信
//======================================
#define P2PMESSAGE 100 // 发送消息
#define P2PMESSAGEACK 101 // 收到消息的应答
#define P2PSOMEONEWANTTOCALLYOU 102 // 服务器向客户端发送的消息
// 希望此客户端发送一个UDP打洞包
#define P2PTRASH 103 // 客户端发送的打洞包,接收端应该忽略此消息
// 客户端之间发送消息格式
struct stP2PMessage
{
int iMessageType;
int iStringLen; // or IP address
unsigned short Port;
};
using namespace std;
typedef list<stUserListNode *> UserList;
#ifndef NATCLIENT_H
#define NATCLIENT_H
#pragma comment(lib,"ws2_32.lib")
#include "windows.h"
#include "..\common\msgproto.h"
#include <iostream>
#include <string.h>
using namespace std;
#include <thread>
#define COMMANDMAXC 25600
#define MAXRETRY 5
class Nat_Client
{
private:
USHORT g_nClientPort ;
USHORT g_nServerPort ;
char UserName[10];
char ServerIP[20];
void command_exit();
void command_send(char * CommandLine);
void command_tell(char * CommandLine);
void command_getu();
bool SendMessageTo(char *UserName, char *Message);
// 接收到P2P的消息
static void command_p2pMsg(sockaddr_in &remote,stP2PMessage &recvbuf,int sinlen);
// 接收到打洞命令,向指定的IP地址打洞
static void command_p2pSomeoneWantToCallYou(sockaddr_in &remote,stP2PMessage &recvbuf,int sinlen);
public:
static UserList ClientList;
static SOCKET PrimaryUDP;
static bool RecvedACK;
Nat_Client();
~Nat_Client();
SOCKET mksock(int type);
void InitWinSock();
stUserListNode GetUser(char *username);
void BindSock(SOCKET sock);
void ConnectToServer(SOCKET sock,char *username, char *serverip);
void OutputUsage();
bool SendMessageTo2(char *UserName, char *Message, const char *pIP, USHORT nPort );
void ParseCommand(char * CommandLine);
static void RecvThreadProc();
void Init();
};
UserList Nat_Client::ClientList ;
bool Nat_Client::RecvedACK;
SOCKET Nat_Client::PrimaryUDP = 0;
Nat_Client::~Nat_Client()
{
command_exit();
Sleep(100);
}
void Nat_Client::command_send(char * CommandLine)
{
char sendname[20];
char message[COMMANDMAXC];
int i;
for(i=5;;i++)
{
if(CommandLine[i]!=' ')
sendname[i-5]=CommandLine[i];
else
{
sendname[i-5]='\0';
break;
}
}
strcpy_s(message,sizeof(message), &(Command