/// <summary> /// Raises the <see cref="ServerError"/> event. /// </summary> protected virtual void OnServerError(Exception error) { try { ServerError?.Invoke(this, new EventArgs()); } catch {} }
/// <summary> /// 等待客户端连接 /// </summary> private void WaitForClientConnection() { Task serverAcceptTask = Task.Factory.StartNew(() => { while (ServerState) { Socket clientSocket = null; try { clientSocket = serverSocket.Accept(); } catch (Exception exception) { ServerError?.Invoke(this, new ServerErrorEventArgs(exception, "服务器意外的被关闭")); break; } switch (ServerAgreement) { case ProtocolType.Tcp: Task task = Task.Run(() => ReceiveMessage(clientSocket)); break; case ProtocolType.Udp: break; } } }); }
public bool Post(string actionName, params object[] value) { var request = WebRequest.Create(this.GetApiUrl(actionName)); try { request.Method = "POST"; request.ContentType = "application/json"; request.Timeout = 3000; object v = null; if (value.Length > 0) { v = value[0]; } using (var sw = new System.IO.StreamWriter(request.GetRequestStream())) { var serializer = new JsonSerializer(); serializer.Serialize(sw, v); } Load(request); return(true); } catch (Exception e) { Response = new Response { Status = -101, Message = e.Message }; ServerError?.Invoke(Response, null); } return(false); }
private void send(IAsyncResult ar) { AsyncObject ao = (AsyncObject)ar.AsyncState; int sendBytes; try { sendBytes = ao.WorkingSocket.EndSend(ar); } catch (Exception ex) { ServerError?.Invoke(new ServerErrorEventArgs(ex, DateTime.Now, this)); return; } if (sendBytes > 0) { byte[] msgByte = new byte[sendBytes]; Array.Copy(ao.Buffer, msgByte, sendBytes); Message msg = new Message(msgByte); SendMessage?.Invoke(new MessageEventArgs(msg, ao.WorkingSocket)); } }
public bool SendToOther(User other, Message message) { foreach (var it in Users) { if (it == other) { continue; } AsyncObject ao = new AsyncObject(1); ao.Buffer = message; ao.WorkingSocket = it.Socket; try { it.Socket.BeginSend(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnSend, ao); } catch (Exception ex) { ServerError?.Invoke(new ServerErrorEventArgs(ex, DateTime.Now, this)); return(false); } } return(true); }
private bool OnServerError(UInt64 serverConnectionHandlerID, string msg, UInt32 error, string extraMsg) { if (ServerError != null) { var args = new ServerErrorEventArgs(new ServerConnectionHandler(serverConnectionHandlerID), (TS3Error)error, msg, extraMsg); ServerError.Invoke(args); return(args.Handled); } return(false); }
private void connect(IAsyncResult ar) { Socket client; try { client = _ServerSocket.EndAccept(ar); } catch (Exception ex) { ServerError?.Invoke(new ServerErrorEventArgs(ex, DateTime.Now, this)); return; } AsyncObject ao = new AsyncObject(4096); ao.WorkingSocket = client; User user = new User(); user.Socket = client; user.Ip = ((IPEndPoint)client.RemoteEndPoint).Address.ToString(); user.Port = ((IPEndPoint)client.RemoteEndPoint).Port; user.Server = this; user.Guid = null; Users.Add(user); Message info = new Message() { Type = MessageType.Info, Text = Data.ServerName }; SendToUser(user, info); info = new Message() { Type = MessageType.Info, Text = Data.MaxUser.GetValueOrDefault().ToString() }; SendToUser(user, info); try { client.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnReceive, ao); } catch (Exception ex) { ServerError?.Invoke(new ServerErrorEventArgs(ex, DateTime.Now, this)); return; } }
/// <summary> /// Shutdown the android server /// </summary> public void CloseServer() { try { serverSocket.Close(); serverSocket.Dispose(); serverSocket = null; } catch (Exception ex) { ServerError?.Invoke(ex); return; } }
/// <summary> /// 关闭指定客户端的端口 /// </summary> /// <param name="userID">客户端的ID</param> /// <param name="port">客户端的端口</param> /// <param name="normal">是否为正常断开</param> /// <param name="exception">异常类型</param> public void CloseClientPort(string userID, int port, bool normal = true, Exception exception = null) { lock (lockObject) { if (clientCollection.RemovePort(userID, port)) { if (normal) { ServerMessage?.Invoke(this, new ServerNotifyEventArgs($"客户端 {userID} 的 {port} 端口断开连接")); return; } ServerMessage?.Invoke(this, new ServerNotifyEventArgs($"客户端 {userID} 的 {port} 端口意外的断开连接")); ServerError?.Invoke(this, new ServerErrorEventArgs(exception, $"客户端 {userID} 的 {port} 端口意外的断开连接")); } } }
public bool SendToUser(User user, Message message) { AsyncObject ao = new AsyncObject(1); ao.Buffer = message; ao.WorkingSocket = user.Socket; try { user.Socket.BeginSend(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnSend, ao); } catch (Exception ex) { ServerError?.Invoke(new ServerErrorEventArgs(ex, DateTime.Now, this)); return(false); } return(true); }
/// <summary> /// 关闭指定客户端 /// </summary> /// <param name="userID">客户端唯一的ID</param> /// <param name="normal">是否为正常断开</param> /// <param name="exception">异常类型</param> public void CloseClient(string userID, bool normal = true, Exception exception = null) { lock (lockObject) { if (clientCollection.ContainClient(userID)) { string ipEndPoint = clientCollection.GetClientIPEndPoint(userID).ToString(); if (clientCollection.RemoveClient(userID)) { ClientOffline?.Invoke(this, new ServerNotifyEventArgs(userID)); if (normal) { ServerMessage?.Invoke(this, new ServerNotifyEventArgs($"客户端 {userID}({ipEndPoint}) 断开连接")); return; } ServerMessage?.Invoke(this, new ServerNotifyEventArgs($"客户端 {userID}({ipEndPoint}) 意外的断开连接")); ServerError?.Invoke(this, new ServerErrorEventArgs(exception, $"客户端 {userID}({ipEndPoint}) 意外的断开连接")); } } } }
public bool Kick(User user, string reason) { try { SendToUser(user, new Message() { Type = MessageType.Kick, Text = reason }); Users.Remove(user); KickedUser?.Invoke(new KickEventArgs(user.Guid, user.Ip, user.Port, reason)); return(true); } catch (Exception ex) { ServerError?.Invoke(new ServerErrorEventArgs(ex, DateTime.Now, this)); return(false); } }
/// <summary> /// Accept new connections /// </summary> /// <param name="ar">Async Result</param> private void AcceptCallback(IAsyncResult ar) { Socket client = null; try { client = serverSocket.EndAccept(ar); } catch (Exception ex) { ServerError?.Invoke(ex); return; } DeviceConnected?.Invoke((IPEndPoint)client.RemoteEndPoint); ReadObject readObject = new ReadObject() { client = client, buffer = new byte[1024], isFirstMessage = true, session = new SessionCrypto() }; client.BeginReceive(readObject.buffer, 0, readObject.buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), readObject); serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null); }
/// <summary> /// The messages from the server are parsed into their types /// and then DeSerialized from their json forms /// </summary> /// <param name="update"></param> private void HandleServerMessage(string update) { if (update.Contains("ErrorType")) { Model.Close(); Application.Current.Dispatcher.Invoke(() => { ServerError?.Invoke(); }); } // Updating the maze in the model automatically updates the VM and the View else if (update.Contains("Maze")) { Maze m = Maze.FromJSON(update); Model.Maze = m; } // The only other message possible is a 'direction' message else if (update.Contains("Direction")) { JObject parse = JObject.Parse(update); MoveEnemy(parse["Direction"].ToString()); } }
/// <summary> /// A helper function used to 'walk' the player from start to end using /// model updates and thread sleeps /// </summary> private void SolutionUpdate() { List <int> coords = Model.TryGetValues(StartPos); // If the solution is -1, there was an error receiving it from the server if (Model.Solution != "-1") { Model.PlayerPosition = StartPos; // We translate the solution into movement and update the position foreach (char instruction in Model.Solution) { System.Threading.Thread.Sleep(250); if (instruction == '0') { coords[0] = coords[0] - 1; } else if (instruction == '1') { coords[0] = coords[0] + 1; } else if (instruction == '2') { coords[1] = coords[1] - 1; } else if (instruction == '3') { coords[1] = coords[1] + 1; } Model.PlayerPosition = String.Format("{0}#{1}", coords[0], coords[1]); } } else { // If the position is -1 we return a server error ServerError?.Invoke(); } }
private void receive(IAsyncResult ar) { AsyncObject ao = (AsyncObject)ar.AsyncState; int recvBytes; try { recvBytes = ao.WorkingSocket.EndReceive(ar); } catch (Exception ex) { ServerError?.Invoke(new ServerErrorEventArgs(ex, DateTime.Now, this)); return; } if (recvBytes > 0) { byte[] msgByte = new byte[recvBytes]; Array.Copy(ao.Buffer, msgByte, recvBytes); Message msg = new Message(msgByte); ReceiveMessage?.Invoke(new MessageEventArgs(msg, ao.WorkingSocket)); } try { ao.WorkingSocket.BeginReceive(ao.Buffer, 0, ao.Buffer.Length, SocketFlags.None, _fnReceive, ao); } catch (Exception ex) { ServerError?.Invoke(new ServerErrorEventArgs(ex, DateTime.Now, this)); return; } }
protected virtual void OnServerError(ServerStartErrorEventArgs e) { ServerError?.Invoke(this, e); }
internal static void InvokeServerError(ServerErrorArgs args) { ServerError?.Invoke(null, args); }
/// <summary> /// Read messages from the device /// </summary> /// <param name="ar">Async Result</param> private void ReadCallback(IAsyncResult ar) { int bytesRead = 0; bool noRead = false; ReadObject readObject = (ReadObject)ar.AsyncState; try { bytesRead = readObject.client.EndReceive(ar); } catch (Exception ex) { ServerError?.Invoke(ex); return; } if (bytesRead > 0) { if (readObject.isFirstMessage) { string derPublicKey = keyGeneration.GetDerPublicKey(); SendString(readObject.client, derPublicKey); Form1.WriteLine("Public Key Sent"); readObject.isFirstMessage = false; } else { byte[] dataReceived = new byte[bytesRead]; Array.Copy(readObject.buffer, dataReceived, bytesRead); string textData = Encoding.UTF8.GetString(dataReceived); if (textData.StartsWith("set-session-key")) { Form1.WriteLine("Got set session key"); string encryptedSessionKey = textData.Substring(15); string sessionKey = Encoding.UTF8.GetString(keyGeneration.DecryptData(Convert.FromBase64String(encryptedSessionKey))); readObject.session.SetSessionKey(sessionKey); } else { Form1.WriteLine("Got session message"); byte[] sessionData = readObject.session.DecryptData(textData); string sessionTextData = Encoding.UTF8.GetString(sessionData); Form1.WriteLine($"Session Data: {sessionTextData}"); if (sessionTextData.StartsWith("res-")) { Form1.WriteLine("Got request setter"); readObject.requestString = sessionTextData.Substring(sessionTextData.IndexOf('-') + 1); Form1.WriteLine($"Request string set to: {readObject.requestString}"); SendString(readObject.client, Convert.ToBase64String(readObject.session.EncryptData(Encoding.UTF8.GetBytes("no-data")))); Form1.WriteLine("Continue message sent to client"); } else if (sessionTextData.StartsWith("no-")) { Form1.WriteLine($"Couldn't find credentials on the device: {sessionTextData}"); string parameter = sessionTextData.Substring(sessionTextData.IndexOf('-') + 1); if (parameter == "setup") { LockStateChanged?.Invoke(LockState.Failed); } else if (parameter == "fp") { Form1.WriteLine("User failed to authenticate with fingerprint!"); if (readObject.requestString == "getkname-windowsLogon") { WindowsLocking.CancelRegistration(); } else if (readObject.requestString.StartsWith("pw-")) { Form1.WriteLine("Password get failed"); if (jsSrv != null) { jsSrv.getPasswordQueue.UpdateState(readObject.requestString.Substring(3), JavascriptServer.CredentialTransferState.Failed); } } else if (readObject.requestString.StartsWith("storpw-")) { Form1.WriteLine("Password storage failed"); if (jsSrv != null) { jsSrv.getPasswordQueue.UpdateState(readObject.requestString.Substring(7), JavascriptServer.CredentialTransferState.Failed); } } else if (readObject.requestString.StartsWith("getkname-")) { Form1.WriteLine("Get key failed"); if (jsSrv != null) { jsSrv.getPasswordQueue.UpdateState(readObject.requestString.Substring(10), JavascriptServer.CredentialTransferState.Failed); } } } noRead = true; } else if (sessionTextData == "getuser") { if (jsSrv == null) { throw new InvalidOperationException("Can't store password while javascript server is down"); } object[] data = jsSrv.storePasswordQueue.GetQueueData(readObject.requestString.Substring(7)); if (data == null || data.Length != 2) { throw new NullReferenceException("Can't find credentials for the specified web site hash"); } readObject.credentials.username = (string)data[0]; readObject.credentials.password = (string)data[1]; SendString(readObject.client, Convert.ToBase64String(readObject.session.EncryptData(Encoding.UTF8.GetBytes(readObject.credentials.username)))); } else if (sessionTextData == "getpass") { SendString(readObject.client, Convert.ToBase64String(readObject.session.EncryptData(Encoding.UTF8.GetBytes(readObject.credentials.password)))); if (jsSrv != null) { jsSrv.storePasswordQueue.UpdateState(readObject.requestString.Substring(7), JavascriptServer.CredentialTransferState.Success); } DismissIfOpen?.Invoke(); noRead = true; } else if (sessionTextData.StartsWith("usresp-")) { string parameter = sessionTextData.Substring(sessionTextData.IndexOf('-') + 1); readObject.credentials.username = parameter; Form1.WriteLine($"Got credentials: usr: {readObject.credentials.username} ; pwd: {readObject.credentials.password}"); if (jsSrv == null) { throw new NullReferenceException("Javascript Server was down when trying to get credentials data"); } jsSrv.getPasswordQueue.UpdateExtraData(readObject.requestString.Substring(3), readObject.credentials.username, readObject.credentials.password); jsSrv.getPasswordQueue.UpdateState(readObject.requestString.Substring(3), JavascriptServer.CredentialTransferState.Success); noRead = true; } else if (sessionTextData.StartsWith("pushkey-")) { string key = sessionTextData.Substring(sessionTextData.IndexOf('-') + 1); if (readObject.requestString == "win") { if (WindowsLocking.IsLogonValid(key)) { LockStateChanged?.Invoke(LockState.Unlocked); } else { LockStateChanged?.Invoke(LockState.Failed); } } else if (readObject.requestString == "lock") { if (WindowsLocking.IsLogonValid(key)) { LockStateChanged?.Invoke(LockState.Locked); } else { LockStateChanged?.Invoke(LockState.Failed); } } else { if (jsSrv == null) { throw new NullReferenceException("Javascript server is down when trying to forward 2fa key"); } jsSrv.getKeyQueue.UpdateExtraData(readObject.requestString.Substring(10), key); jsSrv.getKeyQueue.UpdateState(readObject.requestString.Substring(10), JavascriptServer.CredentialTransferState.Success); } noRead = true; } else if (sessionTextData.StartsWith("pwresp-")) { string parameter = sessionTextData.Substring(sessionTextData.IndexOf('-') + 1); readObject.credentials.password = parameter; DismissIfOpen?.Invoke(); } else if (sessionTextData == "getkvalue") { string parameter = readObject.requestString.Substring(readObject.requestString.IndexOf('-') + 1); string pushKey; if (parameter == "windowsLogon") //Windows Lock Authentication { string lockingKey = WindowsLocking.RegisterLogon(); pushKey = lockingKey; } else { if (jsSrv == null) { throw new NullReferenceException("Javascript server was down when trying to send key to android device"); } if (jsSrv.storeKeyQueue.Contains(readObject.requestString.Substring(9))) { pushKey = (string)jsSrv.storeKeyQueue.GetQueueData(readObject.requestString.Substring(9))[0]; } else { pushKey = "fail"; } } if (pushKey == null) { pushKey = "fail"; } SendString(readObject.client, Convert.ToBase64String(readObject.session.EncryptData(Encoding.UTF8.GetBytes(pushKey)))); if (pushKey == "fail") { Form1.WriteLine("PushKey set to fail!"); jsSrv.storeKeyQueue.UpdateState(readObject.requestString.Substring(9), JavascriptServer.CredentialTransferState.Failed); } else { jsSrv.storeKeyQueue.UpdateState(readObject.requestString.Substring(9), JavascriptServer.CredentialTransferState.Success); } noRead = true; } } } } Array.Clear(readObject.buffer, 0, readObject.buffer.Length); if (!noRead) { readObject.client.BeginReceive(readObject.buffer, 0, readObject.buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), readObject); } }
/// <summary> /// Occurs when the server returns an error code of 500 or higher. /// </summary> /// <param name="e">Arguments for the event.</param> protected virtual void OnServerError(RetryEventArgs e) { ServerError?.Invoke(this, e); }
private void OnConnectionError(Exception exception_) { ServerError?.Invoke(this, exception_); }