public MasterAPI(string[] pcsUrls) { Servers = new ConcurrentDictionary <string, IServer>(); ServerUrls = ""; ServerIdsToUrls = new ConcurrentDictionary <string, string>(); Clients = new ConcurrentDictionary <string, IClient>(); PCSs = new ConcurrentDictionary <string, ProcessCreationService>(); foreach (string url in pcsUrls) { PCSs.TryAdd(BaseUrlExtractor.Extract(url), (ProcessCreationService)Activator.GetObject(typeof(ProcessCreationService), url)); } _startProcessDelegate = new StartProcessDelegate(StartProcess); _serverDelegate = new ServerDelegate(ServerSync); _clientDelegate = new ClientDelegate(ClientSync); _addRoomDelegate = new AddRoomDelegate(AddRoomSync); _statusDelegate = new StatusDelegate(StatusSync); _crashDelegate = new CrashDelegate(CrashSync); _freezeDelegate = new FreezeDelegate(FreezeSync); _unfreezeDelegate = new UnfreezeDelegate(UnfreezeSync); _shutDownSystemDelegate = new ShutDownSystemDelegate(ShutDownSystemSync); _checkNodeStatusDelegate = new CheckNodeStatus(CheckNode); _nodesCreated = 0; }
public async Task Subscribe(ClientDelegate client) { // add action to the list of observers var clientChannel = Channel.CreateBounded <T>(new BoundedChannelOptions(100) { AllowSynchronousContinuations = true, FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true, SingleWriter = true }); var writer = clientChannel.Writer; m_clients = m_clients.Add(writer); try { await client(clientChannel.Reader); } catch (Exception e) { Console.WriteLine(e); throw; } finally { // remove action to the list of observers m_clients = m_clients.Remove(writer); } }
public static void Main(string[] args) { ClientDelegate clientDelegate = new ClientDelegate(Main2); clientDelegate.BeginInvoke(null, null, null); //ローカルのIPアドレスを作成 IPAddress local = IPAddress.Parse("192.168.0.9"); //ポート番号11111でリスナー作成 TcpListener listener = new TcpListener(local, 11111); //リッスン開始 listener.Start(); //TCPクライアントを取得 TcpClient client = listener.AcceptTcpClient(); //通信用のストリームを取得 NetworkStream stream = client.GetStream(); //書き込むデータ。Helloのバイト配列 byte[] data = { 0x48, 0x65, 0x6c, 0x6c, 0x6f }; //TCPクライアントにメッセージを出力 stream.Write(data, 0, data.Length); stream.Close(); client.Close(); listener.Stop(); Console.ReadKey(); }
/// <summary> /// 处理服务器返回的消息 /// </summary> private bool HandleServerData(byte byCheckCode, ushort nMainCmd, ushort nSubCmd, byte[] byBody) { if (byCheckCode != 0) { ClientDelegate.ShowMsgEvent("你的数据已经有误"); return(false); } switch ((EnRoomMainCmdID)nMainCmd) { case EnRoomMainCmdID.MDM_KN_COMMAND: //内核命令 switch ((EnKNSubCmdID)nSubCmd) { case EnKNSubCmdID.SUB_KN_DETECT_SOCKET: SendMessage((ushort)EnRoomMainCmdID.MDM_KN_COMMAND, (ushort)EnKNSubCmdID.SUB_KN_DETECT_SOCKET); break; case EnKNSubCmdID.SUB_KN_SHUT_DOWN_SOCKET: CloseSocket(); break; } break; default: foreach (ClientReadSink sink in m_ReadSinkList) { if (sink != null) { sink.OnServerDataEvent(nMainCmd, nSubCmd, byBody); } } break; } return(true); }
public Client_Window() { InitializeComponent(); textBox1.Text = Properties.Settings.Default.SockerClientIp; textBox2.Text = Properties.Settings.Default.SocketClientPort.ToString(); GetClienLink += Client_.Link; GetClientSend += Client_.SendData; Client_.SetMessage += Message; }
public Client(int id, TcpClient tcpClient, ClientDelegate clientDelegate) { address = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address; connectTime = DateTime.Now; thread = new Thread(ClientThread); thread.IsBackground = true; thread.Priority = ThreadPriority.AboveNormal; networkStream = tcpClient.GetStream(); onDisconnected = clientDelegate; this.ID = id; thread.Start(); }
/// <summary> /// 处理登录完成事件 /// </summary> private bool HandleLogonFinish() { ClientUser user = m_UserList.FindUser(m_Owner.dwUserID); if (user != null) { // 触发登录结束事件 ClientDelegate.OnLogonFinishEvent(); } return(true); }
/// <summary>Add new client(list/log/new thread)</summary> public void AddClient(User client) { if (this.listBox_ClientList.InvokeRequired) { ClientDelegate addClient = new ClientDelegate(AddClient); this.listBox_ClientList.Invoke(addClient, client); } else { this.ClientList.Add(client); this.listBox_ClientList.Items.Add(client.userName); } }
/// <summary>Add new client(list/log/new thread)</summary> public void AddClient( User client ) { if ( this.listBox_ClientList.InvokeRequired ) { ClientDelegate addClient = new ClientDelegate( AddClient ); this.listBox_ClientList.Invoke( addClient , client ); } else { this.ClientList.Add( client ); this.listBox_ClientList.Items.Add( client.userName ); } }
public void Start() { bool bRetCode = false; // 连接服务器 bRetCode = m_RoomSocket.ConnectServer(m_szServerIP, m_nPort); if (!bRetCode) { ClientDelegate.OnShowMsgEvent("连接房间服务器失败"); return; } ClientDelegate.OnShowMsgEvent("连接房间服务器成功"); // 启动处理协程 StartCoroutine(OnHanleDataFiber()); }
public void RemoveClient( User user ) { if ( this.listBox_ClientList.InvokeRequired ) { ClientDelegate removeClient = new ClientDelegate( RemoveClient ); this.listBox_ClientList.Invoke( removeClient , user ); } else { int index = this.ClientList.IndexOf( user ); if ( index >= 0 && index <= this.listBox_ClientList.Items.Count ) { this.listBox_ClientList.Items.RemoveAt( index ); this.ClientList.Remove( user ); } } }
public void RemoveClient(User user) { if (this.listBox_ClientList.InvokeRequired) { ClientDelegate removeClient = new ClientDelegate(RemoveClient); this.listBox_ClientList.Invoke(removeClient, user); } else { int index = this.ClientList.IndexOf(user); if (index >= 0 && index <= this.listBox_ClientList.Items.Count) { this.listBox_ClientList.Items.RemoveAt(index); this.ClientList.Remove(user); } } }
/// <summary> /// 关闭连接 /// </summary> public void CloseSocket() { if (m_ClientSocket == null) { return; } if (!m_ClientSocket.Connected) { m_ClientSocket = null; return; } m_ClientSocket.Shutdown(SocketShutdown.Both); m_ClientSocket.Close(); ClientDelegate.OnShowMsgEvent("关闭了socket"); }
/// <summary> /// 向服务器发送数据(直接向服务器发送数据) /// </summary> public bool SendMessage <T>(ushort wMainCmdID, ushort wSubCmdID, T sendObj) { // 组装数据主体 byte[] byBodyArr = null; try { byBodyArr = ClientConstant.StructureToByte <T>(sendObj); SendMessage(wMainCmdID, wSubCmdID, byBodyArr); } catch (Exception ex) { ClientDelegate.ShowMsgEvent("发送数据错误:" + ex.Message); return(false); } return(true); }
/// <summary> /// 处理框架消息 /// </summary> private void HandleFrameInfo(ushort nSubCmd, byte[] byBody) { switch ((EnGameFrameCmd)nSubCmd) { case EnGameFrameCmd.SUB_GF_OPTION: // CMD_GF_Option go = ClientConstant.ByteToStructure<CMD_GF_Option>(byBody); // m_cbGameStatus = go.bGameStatus; // m_cbAllowLookon = go.bAllowLookon; break; case EnGameFrameCmd.SUB_GF_READY: ClientDelegate.ShowMsgEvent("服务器提问客户端准备好开始了没有"); m_RoomSocket.SendMessage((ushort)EnRoomMainCmdID.MDM_GF_FRAME, (ushort)EnGameFrameCmd.SUB_GF_USER_READY); break; case EnGameFrameCmd.SUB_GF_SCENE: HandleSceneInfo(byBody); break; } }
/// <summary> /// 向服务器发送数据(直接向服务器发送数据) /// </summary> public bool SendMessage <T>(ushort wMainCmdID, ushort wSubCmdID, T sendObj, bool isLogon) { // 组装数据主体 byte[] byBodyArr = new byte[Define.LOGONDATA_LEN]; try { byte[] cbyBodyArr = ClientConstant.StructureToByte <T>(sendObj); Array.Copy(cbyBodyArr, byBodyArr, cbyBodyArr.Length); SendMessage(wMainCmdID, wSubCmdID, byBodyArr); } catch (Exception ex) { ClientDelegate.ShowMsgEvent("发送数据错误:" + ex.Message); return(false); } return(true); }
/// <summary> /// 处理登录消息 /// </summary> private void HandleLogonInfo(ushort nSubCmd, byte[] byBody) { switch ((EnRoomLogonSubCmdID)nSubCmd) { case EnRoomLogonSubCmdID.SUB_GR_LOGON_SUCCESS: { if (byBody.Length != Marshal.SizeOf(new CMD_MB_LogonSuccess())) { ClientDelegate.ShowMsgEvent("登陆成功返回来的数据有误"); return; } CMD_MB_LogonSuccess stLogonSuccess = ClientConstant.ByteToStructure <CMD_MB_LogonSuccess>(byBody); m_Owner.dwUserID = stLogonSuccess.dwUserID; ClientDelegate.ShowMsgEvent("登陆成功:" + stLogonSuccess.szNickName); ClientDelegate.ShowMsgEvent("dwUserID = " + stLogonSuccess.dwUserID); // test.Instance.setText("登陆成功:"+stLogonSuccess.szNickName); UnityEngine.SceneManagement.SceneManager.LoadScene("main"); } break; case EnRoomLogonSubCmdID.SUB_GR_LOGON_ERROR: { if (byBody.Length != Marshal.SizeOf(new CMD_GR_LogonError())) { ClientDelegate.ShowMsgEvent("登陆失败返回来的数据有误"); return; } CMD_GR_LogonError stLogonErr = ClientConstant.ByteToStructure <CMD_GR_LogonError>(byBody); ClientDelegate.ShowMsgEvent("登陆失败"); ClientDelegate.ShowMsgEvent("登陆的错误信息:" + stLogonErr.szErrorDescribe); } break; case EnRoomLogonSubCmdID.SUB_GR_LOGON_FINISH: ClientDelegate.ShowMsgEvent("登陆结束"); HandleLogonFinish(); break; } }
private void AsyncCallClient(ClientDelegate caller, string clientId, string URL, string[] script, IEnumerable <string> serverUrls) { Stopwatch sw = new Stopwatch(); timer.Add(clientId, sw); sw.Start(); caller.BeginInvoke(clientId, URL, script, serverUrls, asyncResult => { timer[clientId].Stop(); TimeSpan elapsed = sw.Elapsed; string elapsedTime = String.Format("{0}", elapsed.Minutes * 60 + elapsed.Seconds + elapsed.Milliseconds / 1000.0); Console.WriteLine("\n[TIMER ALERT] Finished script for client {0}. Elapsed time={1}s\n", clientId, elapsedTime); AsyncResult ar = (AsyncResult)asyncResult; ClientDelegate remoteDel = (ClientDelegate)ar.AsyncDelegate; remoteDel.EndInvoke(asyncResult); }, null); }
/// <summary> /// 连接服务器 /// </summary> public bool ConnectServer(string sServerIP, int nServerPort) { // 连接服务器 try { m_ClientSocket.Connect(sServerIP, nServerPort); } catch (Exception ex) { ClientDelegate.OnShowMsgEvent("连接错误:" + ex.Message); CloseSocket(); return(false); } // 开启接收服务器数据的线程 m_ReceiveThread = new Thread(ReceiveServerMsgThread); m_ReceiveThread.IsBackground = true; m_ReceiveThread.Start(); // 发送第一个检测信号 SendFirstMessage(); return(true); }
/// <summary> /// 接收服务器的数据 /// </summary> private void ReceiveServerMsgThread() { ushort wCmdInfoSize = (ushort)Marshal.SizeOf(new CMD_Info()); ushort wCmdSize = (ushort)Marshal.SizeOf(new CMD_Command()); byte[] byCmdInfoArr = new byte[wCmdInfoSize]; // 命令信息数组 byte[] byCmdArr = new byte[wCmdSize]; // 命令数组 byte[] byBodyArr = null; // 数据主体 byte[] byOneRevBuf = new byte[1024]; // 每次接收数据的缓存 int nOneRevSize = 0; // 每次接收数据的长度 byte[] byAllRevBuf = new byte[1024 * 5]; // 总的接收数据缓冲 ushort nAllRevSize = 0; // 总的接收数据长度 ushort wPacketSize = 0; // 数据包的长度 byte[] byCrevDataArr = null; // 解密出来的数据数组 CMD_Info stCmdInfo; CMD_Command stCmd; while (m_ClientSocket.Connected) { try { nOneRevSize = m_ClientSocket.Receive(byOneRevBuf); if (nOneRevSize <= 0) { m_ClientSocket.Close(); return; } // 缓存数据 Array.Copy(byOneRevBuf, 0, byAllRevBuf, nAllRevSize, nOneRevSize); nAllRevSize += (ushort)nOneRevSize; while (nAllRevSize > wCmdInfoSize) { // 获取数据头部信息 Array.Copy(byAllRevBuf, 0, byCmdInfoArr, 0, wCmdInfoSize);//version,checkcode,size stCmdInfo = ClientConstant.ByteToStructure <CMD_Info>(byCmdInfoArr); wPacketSize = stCmdInfo.wPacketSize; // 缓存的数据是否足够多,来解释出一个数据 if (nAllRevSize < wPacketSize) { break; } // byte[] tmp = new byte[wPacketSize- wCmdInfoSize];// // 网狐映射解密数据 byte byCheckCode = stCmdInfo.cbCheckCode; for (int nI = 4; nI < wPacketSize; nI++) //- wCmdInfoSize { byAllRevBuf[nI] = WHMapEncrypt.MapRecvByte(byAllRevBuf[nI]); byCheckCode += byAllRevBuf[nI]; } // 获取命令 Array.Copy(byAllRevBuf, wCmdInfoSize, byCmdArr, 0, wCmdSize); stCmd = ClientConstant.ByteToStructure <CMD_Command>(byCmdArr); // 获取数据主体 byBodyArr = new byte[wPacketSize - wCmdInfoSize - wCmdSize]; Array.Copy(byAllRevBuf, wCmdSize + wCmdInfoSize, byBodyArr, 0, byBodyArr.Length); // 处理接收到的数据 HandleServerData(byCheckCode, stCmd.wMainCmdID, stCmd.wSubCmdID, byBodyArr); // 清空这次被使用的数据 for (int nI = 0; nI < nAllRevSize - wPacketSize; nI++) { byAllRevBuf[nI] = byAllRevBuf[wPacketSize + nI]; } nAllRevSize -= wPacketSize; } } catch (Exception ex) { ClientDelegate.OnShowMsgEvent("数据异常:" + ex.Message); m_ClientSocket.Close(); break; } } }
public ValidationClient(APIOptions apiOptions, IGenericRepository <Client> repository, ClientDelegate callback) { _apiOptions = apiOptions; _clientRepository = repository; _callback = callback; }
/// <summary> /// 向服务器发送数据(直接向服务器发送数据) /// </summary> public bool SendFirstMessage(ushort wMainCmdID, ushort wSubCmdID, byte[] byBodyArr) { bool bResult = false; CMD_Info stCmdInfo = new CMD_Info(); CMD_Command stCmd = new CMD_Command(); byte[] byEncryBuf = null; // 需要加密的数据的数组 byte[] byCmdArr = null; // 命令数组 byte[] byCmdInfoArr = null; // 命令信息数组 byte[] bySendArr = null; // 需要发送的数据 ushort wPacketSize = 0; // 发送数据的包长 if (m_ClientSocket == null || !m_ClientSocket.Connected) { ClientDelegate.ShowMsgEvent("Socket已经关闭"); return(false); } try { // 组装命令体 stCmd.wMainCmdID = wMainCmdID; stCmd.wSubCmdID = wSubCmdID; byCmdArr = ClientConstant.StructureToByte <CMD_Command>(stCmd); // 组合需要加密的数据 byEncryBuf = new byte[byCmdArr.Length + byBodyArr.Length]; // Array.Copy(byCmdArr, 0, byEncryBuf, 0, byCmdArr.Length); Array.Copy(byBodyArr, 0, byEncryBuf, byCmdArr.Length, byBodyArr.Length - byCmdArr.Length); // 网狐映射加密数据 byte byCheckCode = 0; for (int nI = 0; nI < byEncryBuf.Length; nI++) { byCheckCode += byEncryBuf[nI]; byEncryBuf[nI] = WHMapEncrypt.MapSendByte(byEncryBuf[nI]); } // 数据长度 wPacketSize = (ushort)(byBodyArr.Length + m_nPkgHeaderSize); // 组装命令信息体 stCmdInfo.cbVersion = 0x01; //0x66 stCmdInfo.cbCheckCode = (byte)(~byCheckCode + (byte)1); stCmdInfo.wPacketSize = wPacketSize; byCmdInfoArr = ClientConstant.StructureToByte <CMD_Info>(stCmdInfo); // 整合发送的数据 bySendArr = new byte[byCmdInfoArr.Length + byEncryBuf.Length]; Array.Copy(byCmdInfoArr, 0, bySendArr, 0, byCmdInfoArr.Length); Array.Copy(byEncryBuf, 0, bySendArr, byCmdInfoArr.Length, byEncryBuf.Length); m_ClientSocket.Send(bySendArr); } catch (Exception ex) { ClientDelegate.ShowMsgEvent("发送数据错误:" + ex.Message); } bResult = true; return(bResult); }
/// <summary> /// 处理场景消息 /// </summary> private void HandleSceneInfo(byte[] byBody) { ClientDelegate.ShowMsgEvent("接收到具体游戏的场景了"); // 触发接收场景结束事件 ClientDelegate.OnReceiveSceneFishEvent(); }