/// <summary> /// Send async data to connected socket /// </summary> /// <param name="client"></param> private static void SendReply(ConnectedObject client) { if (client == null) { Console.WriteLine("Ooops, Connection problem."); return; } Console.WriteLine("Proccessing client message"); // TODO function the reverse client message ReverseMessage() string returnMessage = ReverseMessage(client.IncomingMessage); client.SetOutgoingMessage(returnMessage); var byteReply = client.ConvertStringToByte(client.OutgoingMessage); try { client.ClientSocket.BeginSend(byteReply, 0, byteReply.Length, SocketFlags.None, new AsyncCallback((IAsyncResult ar) => { Console.WriteLine("Reply Sent!"); }), client); } catch (SocketException ex) { // Client was forcebly closed on the client side CloseClientSocket(client); Log.Error(ex.Message); } catch (Exception ex) { Log.Error(ex.Message); } }
/// <summary> /// Handler for new connections /// </summary> /// <param name="ar"></param> private static void AcceptCallback(IAsyncResult ar) { PrintConnectionState("Connection received"); // Signal the main thread to continue accepting new connections _connected.Set(); // Accept new client socket connection Socket socket = _server.EndAccept(ar); // Create a new client connection object and store the socket ConnectedObject client = new ConnectedObject(); client.Socket = socket; // Store all clients _clients.Add(client); // Begin receiving messages from new connection try { client.Socket.BeginReceive(client.Buffer, 0, client.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), client); } catch (SocketException) { // Client was forcebly closed on the client side CloseClient(client); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Sends a message to the server /// </summary> /// <param name="client"></param> private static void Send(ConnectedObject client, string userinfo) { // Build message string msg = userinfo; client.CreateOutgoingMessage(msg); byte[] data = client.OutgoingMessageToBytes(); // Send it on a 1 second interval try { client.Socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), client); } catch (SocketException) { Console.WriteLine("Server Closed"); client.Close(); Thread.CurrentThread.Abort(); } catch (Exception ex) { Console.WriteLine(ex.Message); Thread.CurrentThread.Abort(); } }
/// <summary> /// Sends a message to the server /// </summary> /// <param name="client"></param> private static void Send(ConnectedObject client) { // Build message client.CreateOutgoingMessage($"Message from {Console.Title}"); byte[] data = client.OutgoingMessageToBytes(); // Send it on a 1 second interval while (true) { Thread.Sleep(3000); try { client.Socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), client); } catch (SocketException) { Console.WriteLine("Server Closed"); client.Close(); Thread.CurrentThread.Abort(); } catch (Exception ex) { Console.WriteLine(ex.Message); Thread.CurrentThread.Abort(); } } }
private static void AcceptCallback(IAsyncResult ar) { Socket socket; try { _connected.Set(); socket = _server.EndAccept(ar); } catch (ObjectDisposedException) { return; } var client = new ConnectedObject { Socket = socket }; var clientThread = new Thread(() => { try { Receive(client); } catch (ThreadInterruptedException) { // ignored } }); clientThread.Start(); ClientsThreads.Add(clientThread); }
/// <summary> /// Send data async to the connected socket /// </summary> /// <param name="client"></param> private static void Send(ConnectedObject client) { while (true) { resetEvent.Reset(); Console.WriteLine("Please Enter your message:"); client.SetOutgoingMessage(Console.ReadLine()); byte[] byteMessage = client.ConvertStringToByte(client.OutgoingMessage); try { client.ClientSocket.BeginSend(byteMessage, 0, byteMessage.Length, SocketFlags.None, new AsyncCallback((IAsyncResult ar) => { }), client); } catch (SocketException ex) { Log.Error(ex.Message); client.Disconnect(); Thread.CurrentThread.Interrupt(); return; } catch (Exception ex) { Log.Error(ex.Message); Thread.CurrentThread.Interrupt(); return; } resetEvent.WaitOne(); } }
/// <summary> /// Sends a reply to client /// </summary> /// <param name="client"></param> private static void SendReply(ConnectedObject client) { if (client == null) { Console.WriteLine("Unable to send reply: client null"); return; } Console.Write("Sending Reply: "); // Create reply client.CreateOutgoingMessage("Message Received"); var byteReply = client.OutgoingMessageToBytes(); // Listen for more incoming messages try { client.Socket.BeginSend(byteReply, 0, byteReply.Length, SocketFlags.None, new AsyncCallback(SendReplyCallback), client); } catch (SocketException) { // Client was forcebly closed on the client side CloseClient(client); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private static void CloseClient(ConnectedObject client) { client.Close(); if (_clients.Contains(client)) { _clients.Remove(client); } }
/// <summary> /// Closes a client socket and removes it from the client list /// </summary> /// <param name="client"></param> private static void CloseClient(ConnectedObject client) { PrintConnectionState("Client disconnected"); client.Close(); if (_clients.Contains(client)) { _clients.Remove(client); } }
/// <summary> /// Close socket send/receive /// </summary> /// <param name="client"></param> private static void CloseClientSocket(ConnectedObject client) { Console.WriteLine("Client disconnected"); client.Disconnect(); if (Clients.Contains(client)) { Clients.Remove(client); } }
private void AcceptCallBack(IAsyncResult result) { _connected.Set(); ConnectedObject ConnectedObject = new ConnectedObject(_serverSocket.EndAccept(result)); Log.PrintMsg($"New ConnectedObject connect from {ConnectedObject.Socket.RemoteEndPoint}"); _clients.Add(ConnectedObject); Log.PrintMsg($"Total clients: {_clients.Count}"); BeginReceive(ConnectedObject); }
private void BeginReceive(ConnectedObject ConnectedObject) { try { ConnectedObject.Socket.BeginReceive(ConnectedObject.Message.ByteBuffer, 0, GeneralSettings.ByteBufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallBack), ConnectedObject); } catch (SocketException) { CloseClient(ConnectedObject); } }
public void Send(string data) { BarcodeSimulator = new ConnectedObject(); byte[] barcodelength = ConnectedObject.ConvertIntToByteArray16((short)data.Length); _writer.Write(Encoding.ASCII.GetString(BarcodeSimulator.MsgTerminatorStart.ToArray(), 0, BarcodeSimulator.MsgTerminatorStart.Count)); _writer.Write(Encoding.ASCII.GetString(barcodelength, 0, barcodelength.Length)); _writer.Write(data); _writer.Write(Encoding.ASCII.GetString(BarcodeSimulator.MsgTerminatorStop.ToArray(), 0, BarcodeSimulator.MsgTerminatorStop.Count)); _writer.Flush(); }
public void Connect() { client = new ConnectedObject(); // Create a new socket client.Socket = ConnectionManager.CreateSocket(); int attempts = 0; // Loop until we connect (server could be down) while (!client.Socket.Connected) { try { attempts++; Console.WriteLine("Connection attempt " + attempts); // Attempt to connect client.Socket.Connect(ConnectionManager.EndPoint); } catch (SocketException) { Console.Clear(); } } // Display connected status Console.Clear(); PrintConnectionState($"Socket connected to {client.Socket.RemoteEndPoint.ToString()}"); // Start sending & receiving //Thread sendThread = new Thread(() => Send()); // Thread receiveThread = new Thread(() => Receive(client)); Thread CheckIncomingMessageThread = new Thread(() => CheckIncomingMessage()); Thread TriggerThread = new Thread(() => Trigger()); //sendThread.Start(); //receiveThread.Start(); TriggerThread.Start(); Receive(); // Console.WriteLine($"Gia tri cua Buffer list {client.BufferList.Count}"); CheckIncomingMessageThread.Start(); // Listen for threads to be aborted (occurs when socket looses it's connection with the server) //while (sendThread.IsAlive && receiveThread.IsAlive) { } //while ( receiveThread.IsAlive) { } // Attempt to reconnect // Connect(); }
public TcpAsyncClient(ConnectionManager connection) { Client = new ConnectedObject { Name = ClientName, Socket = ConnectionManager.CreateSocket() }; // Create a new socket Client.Socket.Connect(connection.EndPoint); // Receive message from server async Task.Run(() => { while (Receive()) { } }); }
/// <summary> /// Begin receive data from connected socket /// </summary> /// <param name="client"></param> private static void ListenForIncomingMessages(ConnectedObject client) { try { client.ClientSocket.BeginReceive(client.Buffer, 0, client.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveMessages), client); } catch (SocketException ex) { Log.Error(ex.Message); CloseClientSocket(client); } catch (Exception ex) { throw ex; } }
/// <summary> /// Attempts to connect to a server /// </summary> private static void Connect() { ConnectedObject client = new ConnectedObject(); // Create a new socket client.Socket = ConnectionManager.CreateSocket(); int attempts = 0; // Loop until we connect (server could be down) while (!client.Socket.Connected) { try { attempts++; Console.WriteLine("Connection attempt " + attempts); // Attempt to connect client.Socket.Connect(ConnectionManager.EndPoint); } catch (SocketException) { Console.Clear(); } } // Display connected status Console.Clear(); PrintConnectionState($"Socket connected to {client.Socket.RemoteEndPoint.ToString()}"); // Start sending & receiving Thread sendThread = new Thread(() => Send(client)); Thread receiveThread = new Thread(() => Receive(client)); sendThread.Start(); receiveThread.Start(); // Listen for threads to be aborted (occurs when socket looses it's connection with the server) while (sendThread.IsAlive && receiveThread.IsAlive) { } // Attempt to reconnect Connect(); }
private static void Receive(ConnectedObject client) { int bytesRead = 0; while (true) { // Read message from the server try { bytesRead = client.Socket.Receive(client.Buffer, SocketFlags.None); } catch (SocketException) { Console.WriteLine("Server Closed"); client.Close(); Thread.CurrentThread.Abort(); } catch (Exception) { Thread.CurrentThread.Abort(); return; } // Check message if (bytesRead > 0) { // Build message as it comes in client.BuildIncomingMessage(bytesRead); // Check if we received the full message if (client.MessageReceived()) { // Print message to the console Console.WriteLine("Message Received"); // Reset message client.ClearIncomingMessage(); } } } }
public void SendReply(ConnectedObject ConnectedObject, object data) { if (ConnectedObject is null) { Log.PrintMsg("Unable to send reply: ConnectedObject null"); return; } try { Message messageReply = Map.Serialize(data); ConnectedObject.Socket.BeginSend(messageReply.ByteBuffer, 0, messageReply.ByteBuffer.Length, SocketFlags.None, new AsyncCallback(SendReplyCallBack), ConnectedObject); } catch (SocketException exception) { Log.PrintMsg(exception); CloseClient(ConnectedObject); } }
/// <summary> /// Get client object from callback /// </summary> /// <param name="ar"></param> /// <param name="client"></param> /// <returns></returns> private static bool GetClientFromCallback(IAsyncResult ar, out ConnectedObject client) { client = null; if (ar != null) { try { client = (ConnectedObject)ar.AsyncState; return(true); } catch (Exception ex) { Log.Error(ex.Message); } } Console.WriteLine("Ooops, Connection problem."); return(false); }
private static bool Receive(ConnectedObject client) { try { client.Socket.BeginReceive(client.Buffer, 0, client.BufferSize, SocketFlags.None, ReceiveCallback, client); } catch (SocketException) { CloseClient(client); SendLobbyWaitMessage(); return(false); } catch (ObjectDisposedException) { // ignored } return(true); }
private bool CheckState(IAsyncResult result, out string error, out ConnectedObject ConnectedObject) { error = string.Empty; ConnectedObject = null; if (result is null) { error = "Async result null"; return(false); } ConnectedObject = result.AsyncState as ConnectedObject; if (ConnectedObject is null) { error = "Client null"; return(false); } return(true); }
/// <summary> /// Create client socket and connect to IPEndPoint /// </summary> public void Connect() { ConnectedObject client = new ConnectedObject(); client.ClientSocket = NetworkManager.CreateSocket(); int connectAttempt = 0; while (!client.ClientSocket.Connected && connectAttempt < 3) { try { connectAttempt++; Console.WriteLine("Connection attempt " + connectAttempt); // Attempt to connect client.ClientSocket.Connect(NetworkManager.IPEndPoint); } catch (SocketException ex) { Log.Error(ex.Message); Console.Clear(); } } // Maximum attempts to connect if (!client.ClientSocket.Connected) { Console.WriteLine("Connect unsuccessful"); Console.ReadLine(); } Thread sendThread = new Thread(() => Send(client)); Thread receiveThread = new Thread(() => Receive(client)); sendThread.Start(); receiveThread.Start(); }
/// <summary> /// Checks IAsyncResult for null value /// </summary> /// <param name="ar"></param> /// <param name="err"></param> /// <param name="client"></param> /// <returns></returns> private static bool CheckState(IAsyncResult ar, out string err, out ConnectedObject client) { // Initialise client = null; err = ""; // Check ar if (ar == null) { err = "Async result null"; return(false); } // Check client client = (ConnectedObject)ar.AsyncState; if (client == null) { err = "Client null"; return(false); } return(true); }
public static void SendLobbyRejectMessage(ConnectedObject client) { var clientData = new LobbyWaitData { ClientName = _serverName, Status = ReceiverStatus.Rejected }; try { client.Socket.SendTo(Encoding.UTF8.GetBytes(clientData.ToString()), client.Socket.RemoteEndPoint); } catch (SocketException) { SendLobbyWaitMessage(); } catch (ObjectDisposedException) { // ignored } catch (Exception) { SendLobbyWaitMessage(); } }
private static void Connect(string userinfo) { ConnectedObject client = new ConnectedObject(); // Create a new socket client.Socket = ConnectionManager.CreateSocket(); int attempts = 0; // Loop until we connect (server could be down) while (!client.Socket.Connected) { try { attempts++; Console.WriteLine("Connection attempt " + attempts); // Attempt to connect client.Socket.Connect(ConnectionManager.EndPoint); } catch (SocketException) { Console.Clear(); } } // Display connected status Console.Clear(); PrintConnectionState($"Socket connected to {client.Socket.RemoteEndPoint.ToString()}"); // Start sending & receiving Thread sendThread = new Thread(() => Send(client, userinfo)); sendThread.Start(); // Attempt to reconnect Connect(userinfo); }
/// <summary> /// Receive data from a bound socket /// </summary> /// <param name="client"></param> private static void Receive(ConnectedObject client) { int bytesRead = 0; while (true) { try { bytesRead = client.ClientSocket.Receive(client.Buffer, SocketFlags.None); } catch (SocketException ex) { Log.Error(ex.Message); client.Disconnect(); Console.WriteLine("Server Disconnect"); } catch (Exception ex) { Log.Error(ex.Message); } if (bytesRead > 0) { if (bytesRead > 0) { client.SetIncomingMessage(bytesRead); Console.WriteLine(client.IncomingMessage); bytesRead = 0; resetEvent.Set(); } } } }
/// <summary> /// Callback for handling client connection /// </summary> /// <param name="ar"></param> private static void HandleClientConnect(IAsyncResult ar) { Console.WriteLine("New Connection"); resetEvent.Set(); try { Socket clientSocket = ServerSocket.EndAccept(ar); ConnectedObject client = new ConnectedObject() { ClientSocket = clientSocket }; Clients.Add(client); ListenForIncomingMessages(client); } catch (Exception ex) { Log.Error(ex.Message); } }
public Client() { ConnectedObject = new ConnectedObject(ConnectionHandler.CreateSocket()); }
private static void Receive(ConnectedObject client, LoginScreen parent) { int bytesRead = 0; while (true) { // Read message from the server try { bytesRead = client.Socket.Receive(client.Buffer, SocketFlags.None); } catch (SocketException) { Console.WriteLine("Server Closed"); client.Close(); Thread.CurrentThread.Abort(); } catch (Exception) { Thread.CurrentThread.Abort(); return; } // Check message if (bytesRead > 0) { // Build message as it comes in client.BuildIncomingMessage(bytesRead); // Check if we received the full message if (client.MessageReceived()) { // Print message to the console Console.WriteLine("Message Received"); Console.WriteLine(client.getIncommingMessage()); string response = client.getIncommingMessage().Replace("<END>", ""); if (int.Parse(response.Split(',')[0]) == 1) { parent.SetVisible(true); parent.SetText("This Key Got Banned !"); parent.SetColor(System.Drawing.Color.Red); } else if (int.Parse(response.Split(',')[0]) == 2) { parent.SetVisible(true); parent.SetText("Password Wrong !"); parent.SetColor(System.Drawing.Color.Red); } else if (int.Parse(response.Split(',')[0]) == 3) { parent.SetVisible(true); parent.SetText("Key Already Online !"); parent.SetColor(System.Drawing.Color.Yellow); } else if (int.Parse(response.Split(',')[0]) == 4) { parent.SetVisible(true); parent.SetText("Key Binded Click Login Again !"); parent.SetColor(System.Drawing.Color.Lime); } else if (int.Parse(response.Split(',')[0]) == 5) { parent.SetVisible(true); parent.SetText("Key Deleted Because Expired !"); parent.SetColor(System.Drawing.Color.Red); } else if (int.Parse(response.Split(',')[0]) == 6) { parent.SetVisible(true); parent.SetText("Your Key Expired !"); parent.SetColor(System.Drawing.Color.Red); } else if (int.Parse(response.Split(',')[0]) == 7) { parent.SetVisible(true); parent.SetText("You Can't Use On This PC !"); parent.SetColor(System.Drawing.Color.Red); } else if (int.Parse(response.Split(',')[0]) == 8) { parent.SetVisible(true); parent.SetText("You Have Been Banned !"); parent.SetColor(System.Drawing.Color.Red); } else if (int.Parse(response.Split(',')[0]) == 9) { string message1 = "VERSION OUTDATED , PLEASE CLICK OK TO UPDATE OR CANCEL TO SHUTDOWN !"; string title1 = "! BYPASS WARNING !"; MessageBoxButtons buttons1 = MessageBoxButtons.OKCancel; DialogResult result1 = MessageBox.Show(message1, title1, buttons1, MessageBoxIcon.Warning); if (result1 == DialogResult.OK) { updater.DoUpdate(); } else if (result1 == DialogResult.Cancel) { Application.Exit(); } } else if (int.Parse(response.Split(',')[0]) == 10) { parent.SetVisible(false); parent.SafeHide(); using (RegistryKey Key = Registry.CurrentUser.OpenSubKey(@"Techcom", true)) if (Key != null) { string val = (string)Key.GetValue("Name"); if (string.IsNullOrEmpty(val)) { Key.SetValue("Name", "" + response.Split(',')[1] + ""); Key.Close(); } else { Key.SetValue("Name", "" + response.Split(',')[1] + ""); Key.Close(); } } else { RegistryKey key; key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Techcom"); key.SetValue("Name", "" + response.Split(',')[1] + ""); key.Close(); } BypassScreen bypassdialog = new BypassScreen(); TimeSpan timeSpan = new TimeSpan(DateTime.ParseExact(response.Split(',')[2], "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture).Ticks); DateTime nistTime = DateTime.Now; TimeSpan timeSpan1 = new TimeSpan(nistTime.Ticks); int totalDays = (int)(timeSpan.TotalDays - timeSpan1.TotalDays); int totalHours = (int)(timeSpan.TotalHours - timeSpan1.TotalHours); int totalMinutes = (int)(timeSpan.TotalMinutes - timeSpan1.TotalMinutes); string str1 = ""; string str2 = ""; if (totalDays > 0) { str1 = string.Concat("Expire By Days : ", totalDays, " Days"); str2 = string.Concat("", totalDays, " Days"); } else if (totalHours > 0) { str1 = string.Concat("Expire By Hours: ", totalHours, " Hours"); str2 = string.Concat("", totalHours, " Hours"); } else if (totalMinutes > 0) { str1 = string.Concat("Expire By Minutes : ", totalMinutes, " Minutes"); str2 = string.Concat("", totalMinutes, " Minutes"); } bypassdialog.Show(); Control[] ctrls = bypassdialog.Controls.Find("username", false); if (ctrls.Length > 0) { Label lbl = (Label)ctrls[0]; lbl.Text += response.Split(',')[1]; } Control[] ctrls2 = bypassdialog.Controls.Find("keyindays", false); if (ctrls2.Length > 0) { Label lbl = (Label)ctrls2[0]; lbl.Text = str1; } Control[] ctrls3 = bypassdialog.Controls.Find("keyindate", false); if (ctrls3.Length > 0) { Label lbl = (Label)ctrls3[0]; lbl.Text = "Expire By Date : " + response.Split(',')[2] + ""; } bypassdialog.Text += str2; parent.SafeHide(); } // Reset message client.ClearIncomingMessage(); } } } }