public static bool sendPacket(string msg, Socket clientSocket) { if (!clientSocket.Connected) { throw new IOException("You are not connected!"); } if (msg.Length > 0) { try { NetworkStream stream = new NetworkStream(clientSocket); byte[] outBMsg = Encoding.UTF8.GetBytes(msg); byte[] outB = new byte[outBMsg.Length + 4]; byte[] outLenB = System.BitConverter.GetBytes(msg.Length + 4); outLenB.CopyTo(outB, 0); outBMsg.CopyTo(outB, 4); stream.Write(outB, 0, outB.Length); return(true); } catch (IOException e) { CDialogManager.ShowExceptionDialog(e, "Error while sending msg"); } } return(false); }
private void ExecuteMsg() { String input = ""; try { input = ConsoleInput.Text; if (!input.StartsWith("!")) { input = "!say " + input; } var CM = MainWindow.instance.CommandManager; WriteLine(input); if (CM.ExecuteCommand(input, Conn)) { ConsoleInput.Text = ""; Command cmd = Command.GetCommand(input); if (cmd != Command.GetCommand(Commands.NONE) && cmd != Command.GetCommand(Commands.ERROR)) { int len; if (cmd != Command.GetCommand(Commands.SAY)) { len = 0; } else { len = cmd.CommandString.Length; } CM.AddCommandToList(input.Substring(len, input.Length - len)); WriteLine("Command executed"); } else { WriteLine("Command executed but there was something wrong", Brushes.Yellow); } } else { WriteLine("Command not executed!", Brushes.Red); } } catch (Exception ex) { CDialogManager.ShowExceptionDialog(ex, "You are disconnected!"); Conn.Disconnect(); } Send_Button.SetResourceReference(Control.IsEnabledProperty, "Connected"); }
public void Connect() { int Port = EST_PORT; serverAddress = new IPEndPoint(IPAddress.Parse(localIP), Port); _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { _clientSocket.Connect(serverAddress); Connected = true; listener.startListening(); } catch (SocketException ex) { CDialogManager.ShowExceptionDialog(ex, "Connection on address " + serverAddress.Address.ToString() + ":" + Port + " not found."); Connected = false; } }
public void run() { MainWindow MWindow = MainWindow.instance; try { while (MWindow.Conn.Connected && listening) { String msg = PacketParser.receivePacket(Conn.ClientSocket); if (!msg.Equals("")) { if (MWindow.CommandManager.ExecuteCommand(msg, Conn, true)) { Console.WriteLine("ServerSide Command executed: " + msg); } else { Console.WriteLine("ServerSide Command not executed: " + msg); } } try { Thread.Sleep(1000); } catch (ThreadInterruptedException ex) { CDialogManager.ShowExceptionDialog(ex, null); } } } catch (IOException e) { CDialogManager.ShowExceptionDialog(e, null); Conn.Disconnect(); } }