HGGitLab

Commit bdf876f6 authored by luoliangyi's avatar luoliangyi

增加websocket工程,实现和浏览器交互websocket协议的基础功能

parent 0a8765ad
......@@ -6,7 +6,7 @@
****************************************************************************/
/* Microsoft C/C++ Compiler */
#if defined(WIN32) || defined(WIN64) || defined (_WINDOWS)
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined (_WINDOWS)
#define HG_CMP_MSC
#if defined(_WIN64) || defined(WIN64)
......
......@@ -16,6 +16,7 @@
#if defined(HG_CMP_MSC)
#include <windows.h>
#include <WinSock2.h>
#else
#include <sys/time.h>
#include <errno.h>
......
......@@ -34,6 +34,15 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HGSaneUser", "HGSaneUser\HG
{F85F4457-1B42-46E7-BA86-F088D6D5994F} = {F85F4457-1B42-46E7-BA86-F088D6D5994F}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HGWebService", "HGWebService\HGWebService.vcxproj", "{BA4F1937-479E-463C-BB25-0DAC454DB625}"
ProjectSection(ProjectDependencies) = postProject
{F85F4457-1B42-46E7-BA86-F088D6D5994F} = {F85F4457-1B42-46E7-BA86-F088D6D5994F}
{EFAE5F69-A4C2-4A07-8BE6-68714D86BCE2} = {EFAE5F69-A4C2-4A07-8BE6-68714D86BCE2}
{4954F36B-A0A3-4550-9C4E-3B3D210F5CE4} = {4954F36B-A0A3-4550-9C4E-3B3D210F5CE4}
{5D85F2AC-FACD-436C-A67B-E13056DD0C03} = {5D85F2AC-FACD-436C-A67B-E13056DD0C03}
{4909ACEA-80FF-482E-9FA2-5E8534789A82} = {4909ACEA-80FF-482E-9FA2-5E8534789A82}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
......@@ -90,6 +99,14 @@ Global
{4954F36B-A0A3-4550-9C4E-3B3D210F5CE4}.Release|x64.Build.0 = Release|x64
{4954F36B-A0A3-4550-9C4E-3B3D210F5CE4}.Release|x86.ActiveCfg = Release|Win32
{4954F36B-A0A3-4550-9C4E-3B3D210F5CE4}.Release|x86.Build.0 = Release|Win32
{BA4F1937-479E-463C-BB25-0DAC454DB625}.Debug|x64.ActiveCfg = Debug|x64
{BA4F1937-479E-463C-BB25-0DAC454DB625}.Debug|x64.Build.0 = Debug|x64
{BA4F1937-479E-463C-BB25-0DAC454DB625}.Debug|x86.ActiveCfg = Debug|Win32
{BA4F1937-479E-463C-BB25-0DAC454DB625}.Debug|x86.Build.0 = Debug|Win32
{BA4F1937-479E-463C-BB25-0DAC454DB625}.Release|x64.ActiveCfg = Release|x64
{BA4F1937-479E-463C-BB25-0DAC454DB625}.Release|x64.Build.0 = Release|x64
{BA4F1937-479E-463C-BB25-0DAC454DB625}.Release|x86.ActiveCfg = Release|Win32
{BA4F1937-479E-463C-BB25-0DAC454DB625}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\..\sdk\webservice\main.cpp" />
<ClCompile Include="..\..\..\sdk\webservice\WSServer.cpp" />
<ClCompile Include="..\..\..\sdk\webservice\WSUser.cpp" />
<ClCompile Include="..\..\..\third_party\base64\base64.cpp" />
<ClCompile Include="..\..\..\third_party\sha1\sha1.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\..\sdk\webservice\WSMsg.h" />
<ClInclude Include="..\..\..\sdk\webservice\WSServer.h" />
<ClInclude Include="..\..\..\sdk\webservice\WSUser.h" />
<ClInclude Include="..\..\..\third_party\base64\base64.h" />
<ClInclude Include="..\..\..\third_party\sha1\sha1.h" />
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{ba4f1937-479e-463c-bb25-0dac454db625}</ProjectGuid>
<RootNamespace>HGWebService</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_CONSOLE;_WINSOCK_DEPRECATED_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<AdditionalIncludeDirectories>../../../third_party/sha1/;../../../third_party/base64/;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>../Debug/HGBase.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_CONSOLE;_WINSOCK_DEPRECATED_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<AdditionalIncludeDirectories>../../../third_party/sha1/;../../../third_party/base64/;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>../Release/HGBase.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
<PostBuildEvent>
<Command>copy $(OutDir)HGWebService.exe $(SolutionDir)..\..\release\bin\windows\x86\</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_WINDOWS;_CONSOLE;_WINSOCK_DEPRECATED_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<AdditionalIncludeDirectories>../../../third_party/sha1/;../../../third_party/base64/;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>../x64/Debug/HGBase.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_WINDOWS;_CONSOLE;_WINSOCK_DEPRECATED_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<AdditionalIncludeDirectories>../../../third_party/sha1/;../../../third_party/base64/;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>../x64/Release/HGBase.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
<PostBuildEvent>
<Command>copy $(OutDir)HGWebService.exe $(SolutionDir)..\..\release\bin\windows\x64\</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
\ No newline at end of file
......@@ -6,7 +6,7 @@
****************************************************************************/
/* Microsoft C/C++ Compiler */
#if defined(WIN32) || defined(WIN64) || defined (_WINDOWS)
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined (_WINDOWS)
#define HG_CMP_MSC
#if defined(_WIN64) || defined(WIN64)
......
......@@ -16,6 +16,7 @@
#if defined(HG_CMP_MSC)
#include <windows.h>
#include <WinSock2.h>
#else
#include <sys/time.h>
#include <errno.h>
......
#ifndef __WSMSG_H__
#define __WSMSG_H__
#include "../../base/HGDef.h"
#define WS_MSGID_QUIT 1
#define WS_MSGID_CONNET 2
#define WS_MSGID_DISCONNET 3
#define WS_MSGID_PONG 4
#define WS_MSGID_WSCMD 5
struct WSMsg
{
HGUInt id; /* WS_MSGID_** */
HGPointer param1;
HGPointer param2;
};
struct ConnectParam
{
HGChar ip[16];
HGUShort port;
#if defined(HG_CMP_MSC)
SOCKET socket;
#else
int socket;
#endif
};
#endif /* __WSMSG_H__ */
#include "WSServer.h"
#include "WSUser.h"
WSServer::WSServer()
{
m_nCurrId = 0;
HGBase_CreateEvent(HGTRUE, HGFALSE, &m_msgEvent);
HGBase_CreateLock(&m_msgLock);
HGBase_CreateLock(&m_csUser);
m_bRecvMsg = HGFALSE;
#if defined(HG_CMP_MSC)
m_sockServer = INVALID_SOCKET;
#else
m_sockServer = -1;
#endif
m_listenThread = NULL;
}
WSServer::~WSServer()
{
HGBase_DestroyLock(m_csUser);
m_csUser = NULL;
HGBase_DestroyLock(m_msgLock);
m_msgLock = NULL;
HGBase_DestroyEvent(m_msgEvent);
m_msgEvent = NULL;
}
bool WSServer::SendMsg(const WSMsg *msg)
{
if (NULL == msg)
{
return false;
}
bool ret = false;
HGBase_EnterLock(m_msgLock);
if (m_bRecvMsg)
{
m_listMsg.push_back(*msg);
HGBase_SetEvent(m_msgEvent);
if (WS_MSGID_QUIT == msg->id)
{
m_bRecvMsg = HGFALSE;
}
ret = true;
}
HGBase_LeaveLock(m_msgLock);
if (ret)
{
//
}
return ret;
}
bool WSServer::Open(HGUShort port)
{
#if defined(HG_CMP_MSC)
if (INVALID_SOCKET != m_sockServer)
#else
if (-1 != m_sockServer)
#endif
{
return false;
}
#if defined(HG_CMP_MSC)
SOCKET sockServer = socket(AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == sockServer)
#else
int sockServer = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == sockServer)
#endif
{
printf("open websocket-server failed 1\n");
return false;
}
// bind
#if defined(HG_CMP_MSC)
SOCKADDR_IN addrServer;
addrServer.sin_addr.S_un.S_addr = INADDR_ANY;
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(port);
if (0 != bind(sockServer, (SOCKADDR *)&addrServer, sizeof(SOCKADDR_IN)))
#else
struct sockaddr_in addrServer;
addrServer.sin_addr.s_addr = htonl(INADDR_ANY);
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(port);
if (0 != bind(sockServer, (struct sockaddr *)&addrServer, sizeof(addrServer)))
#endif
{
#if defined(HG_CMP_MSC)
closesocket(sockServer);
#else
close(sockServer);
#endif
printf("open websocket-server failed 2\n");
return false;
}
// listen
if (0 != listen(sockServer, 5))
{
#if defined(HG_CMP_MSC)
closesocket(sockServer);
#else
close(sockServer);
#endif
printf("open websocket-server failed 3\n");
return false;
}
HGBase_EnterLock(m_msgLock);
m_bRecvMsg = HGTRUE;
HGBase_LeaveLock(m_msgLock);
m_sockServer = sockServer;
HGBase_OpenThread(ThreadFunc, this, &m_listenThread);
assert(NULL != m_listenThread);
printf("open websocket-server success\n");
return true;
}
bool WSServer::Close()
{
#if defined(HG_CMP_MSC)
if (INVALID_SOCKET == m_sockServer)
#else
if (-1 == m_sockServer)
#endif
{
return false;
}
#if defined(HG_CMP_MSC)
closesocket(m_sockServer);
m_sockServer = INVALID_SOCKET;
#else
close(m_sockServer);
m_sockServer = -1;
#endif
HGBase_CloseThread(m_listenThread);
m_listenThread = NULL;
return true;
}
void WSServer::MsgLoop()
{
while (1)
{
HGBase_WaitEvent(m_msgEvent);
WSMsg msg = {0};
HGBase_EnterLock(m_msgLock);
if (!m_listMsg.empty())
{
msg = m_listMsg.front();
m_listMsg.pop_front();
}
HGBase_LeaveLock(m_msgLock);
switch (msg.id)
{
case WS_MSGID_QUIT:
{
while (!m_vectorUser.empty())
{
HGBase_EnterLock(m_csUser);
WSUser *pUser = m_vectorUser[0];
m_vectorUser.erase(m_vectorUser.begin());
HGBase_LeaveLock(m_csUser);
delete pUser;
pUser = NULL;
}
}
break;
case WS_MSGID_CONNET:
{
ConnectParam *param = (ConnectParam *)msg.param2;
assert(NULL != param);
WSUser *user = new WSUser(this, param->ip, param->port, param->socket);
HGBase_EnterLock(m_csUser);
m_vectorUser.push_back(user);
HGBase_LeaveLock(m_csUser);
delete param;
}
break;
case WS_MSGID_DISCONNET:
{
std::string *guid = (std::string *)msg.param1;
assert(NULL != guid);
int nIndex = GetUserIndex(*guid);
if (-1 != nIndex)
{
HGBase_EnterLock(m_csUser);
WSUser *pUser = m_vectorUser[nIndex];
m_vectorUser.erase(m_vectorUser.begin() + nIndex);
HGBase_LeaveLock(m_csUser);
delete pUser;
pUser = NULL;
}
delete guid;
}
break;
case WS_MSGID_PONG:
{
std::string *guid = (std::string *)msg.param1;
assert(NULL != guid);
int nIndex = GetUserIndex(*guid);
if (-1 != nIndex)
{
m_vectorUser[nIndex]->Pong();
}
delete guid;
}
break;
case WS_MSGID_WSCMD:
{
std::string *guid = (std::string *)msg.param1;
assert(NULL != guid);
std::string *info = (std::string *)msg.param2;
assert(NULL != info);
int nIndex = GetUserIndex(*guid);
if (-1 != nIndex)
{
m_vectorUser[nIndex]->HandleWSCmd(info->c_str());
}
delete info;
delete guid;
}
break;
}
HGBase_EnterLock(m_msgLock);
if (m_listMsg.empty())
{
HGBase_ResetEvent(m_msgEvent);
}
HGBase_LeaveLock(m_msgLock);
if (WS_MSGID_QUIT == msg.id)
{
break;
}
}
}
bool WSServer::GetGuidString(char *pszString, uint32_t *pnLen)
{
++m_nCurrId;
sprintf(pszString, "%u", m_nCurrId);
if (NULL != pnLen)
*pnLen = (uint32_t)strlen(pszString) + 1;
return true;
}
int WSServer::GetUserIndex(const std::string &guid)
{
int nIndex = -1;
for (int i = 0; i < (int)m_vectorUser.size(); ++i)
{
if (guid == m_vectorUser[i]->GetGuid())
{
nIndex = i;
break;
}
}
return nIndex;
}
void WSServer::ThreadFunc(HGThread thread, HGPointer param)
{
WSServer *p = (WSServer *)param;
while (1)
{
#if defined(HG_CMP_MSC)
SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR_IN);
SOCKET socketConn = accept(p->m_sockServer, (SOCKADDR *)&addrClient, &len);
if (INVALID_SOCKET == socketConn)
#else
struct sockaddr_in addrClient;
socklen_t len = sizeof(addrClient);
int socketConn = accept(p->m_sockServer, (struct sockaddr *)&addrClient, &len);
if (-1 == socketConn)
#endif
{
// 这里跳出,可能是服务器关闭了m_sockServer
break;
}
ConnectParam *param = new ConnectParam;
strcpy(param->ip, inet_ntoa(addrClient.sin_addr));
param->port = ntohs(addrClient.sin_port);
param->socket = socketConn;
WSMsg msg;
msg.id = WS_MSGID_CONNET;
msg.param1 = 0;
msg.param2 = param;
bool b = p->SendMsg(&msg);
if (!b)
{
delete param;
#if defined(HG_CMP_MSC)
closesocket(socketConn);
#else
close(socketConn);
#endif
}
}
}
#ifndef __WSSERVER_H__
#define __WSSERVER_H__
#include "../../base/HGDef.h"
#include "../../base/HGInc.h"
#include "../../base/HGEvent.h"
#include "../../base/HGLock.h"
#include "../../base/HGThread.h"
#include "WSMsg.h"
#include <string>
#include <vector>
#include <list>
class WSServer
{
public:
WSServer();
~WSServer();
bool SendMsg(const WSMsg *msg);
bool Open(HGUShort port);
bool Close();
void MsgLoop();
bool GetGuidString(char *pszString, uint32_t *pnLen);
private:
int GetUserIndex(const std::string &guid);
static void ThreadFunc(HGThread thread, HGPointer param);
private:
HGUInt m_nCurrId;
HGEvent m_msgEvent;
HGLock m_msgLock;
HGLock m_csUser;
HGBool m_bRecvMsg;
std::list<WSMsg> m_listMsg;
#if defined(HG_CMP_MSC)
SOCKET m_sockServer;
#else
int m_sockServer;
#endif
HGThread m_listenThread;
std::vector<class WSUser *> m_vectorUser;
};
#endif /* __WSSERVER_H__ */
This diff is collapsed.
#ifndef __WSUSER_H__
#define __WSUSER_H__
#include "../../base/HGDef.h"
#include "../../base/HGInc.h"
#include "../../base/HGLock.h"
#include "../../base/HGThread.h"
#include <string>
class WSUser
{
public:
#if defined(HG_CMP_MSC)
WSUser(class WSServer *server, const char *ip, uint16_t port, SOCKET sockConn);
#else
WSUser(class WSServer *server, const char *ip, uint16_t port, int sockConn);
#endif
~WSUser();
std::string GetGuid();
void Pong();
void HandleWSCmd(const char *info);
private:
void HandleWSCmd(const uint8_t *pData, int nDataSize);
bool SendWSFrame(const uint8_t *pBuffer, uint32_t nBufferSize);
static void WSThreadFunc(HGThread thread, HGPointer param);
private:
class WSServer *m_server;
HGLock m_cs;
char m_guid[512];
char m_ip[16];
uint16_t m_port;
#if defined(HG_CMP_MSC)
SOCKET m_sockConn;
#else
int m_sockConn;
#endif
HGThread m_wsThread;
};
#endif /* __WSUSER_H__ */
#include "../../base/HGDef.h"
#include "../../base/HGInc.h"
#include "../../base/HGThread.h"
#include "WSServer.h"
static void ServerThreadFunc(HGThread thread, HGPointer param)
{
WSServer* server = (WSServer*)param;
if (server->Open(36668))
{
server->MsgLoop();
server->Close();
}
}
int main()
{
#if defined(HG_CMP_MSC)
WSADATA ws = { 0 };
int ret = WSAStartup(MAKEWORD(2, 2), &ws);
assert(0 == ret);
#endif
WSServer server;
HGThread serverThread = NULL;
HGBase_OpenThread(ServerThreadFunc, &server, &serverThread);
HGBase_CloseThread(serverThread);
serverThread = NULL;
#if defined(HG_CMP_MSC)
WSACleanup();
#endif
return 0;
}
\ No newline at end of file
/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
#include "base64.h"
#include <iostream>
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
std::string base64_decode(std::string const& encoded_string) {
size_t in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = (unsigned char)base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = (unsigned char)base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
#include <string>
std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const& s);
This diff is collapsed.
/*
* sha1.h
*
* Copyright (C) 1998, 2009
* Paul E. Jones <paulej@packetizer.com>
* All Rights Reserved.
*
*****************************************************************************
* $Id: sha1.h 12 2009-06-22 19:34:25Z paulej $
*****************************************************************************
*
* Description:
* This class implements the Secure Hashing Standard as defined
* in FIPS PUB 180-1 published April 17, 1995.
*
* Many of the variable names in this class, especially the single
* character names, were used because those were the names used
* in the publication.
*
* Please read the file sha1.cpp for more information.
*
*/
#ifndef _SHA1_H_
#define _SHA1_H_
class SHA1
{
public:
SHA1();
virtual ~SHA1();
/*
* Re-initialize the class
*/
void Reset();
/*
* Returns the message digest
*/
bool Result(unsigned *message_digest_array);
/*
* Provide input to SHA1
*/
void Input( const unsigned char *message_array,
unsigned length);
void Input( const char *message_array,
unsigned length);
void Input(unsigned char message_element);
void Input(char message_element);
SHA1& operator<<(const char *message_array);
SHA1& operator<<(const unsigned char *message_array);
SHA1& operator<<(const char message_element);
SHA1& operator<<(const unsigned char message_element);
private:
/*
* Process the next 512 bits of the message
*/
void ProcessMessageBlock();
/*
* Pads the current message block to 512 bits
*/
void PadMessage();
/*
* Performs a circular left shift operation
*/
inline unsigned CircularShift(int bits, unsigned word);
unsigned H[5]; // Message digest buffers
unsigned Length_Low; // Message length in bits
unsigned Length_High; // Message length in bits
unsigned char Message_Block[64]; // 512-bit message blocks
int Message_Block_Index; // Index into message block array
bool Computed; // Is the digest computed?
bool Corrupted; // Is the message digest corruped?
};
#endif // _SHA1_H_
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment