public void Start(int port = 7788) { try { Host = new SimpleTcpServer(); Host.DataReceived += Host_DataReceived; Host.ClientConnected += (o, e) => { for (int i = Clients.Count - 1; i >= 0; i--) { if (!Clients[i].Connected) { Clients.RemoveAt(i); } } Clients.Add(e); Console.WriteLine("Client Connected"); }; Host.Start(port); Settings.IsServer = true; Settings.InvokeConnection(); } catch (Exception) { Settings.IsServer = false; MessageBox.Show("Kunne ikke starte serveren.\nTjek at porten ikke bliver brugt.", "Server ikke startet", MessageBoxButton.OK, MessageBoxImage.Error); } }
public bool Connect(string ipAddress = "127.0.0.1", int port = 7788) { try { client = new SimpleTcpClient(); client.DataReceived += Client_DataReceived; // client.TcpClient.Client..SetSocketOption(System.Net.Sockets.SocketOptionLevel.Tcp, System.Net.Sockets.SocketOptionName.KeepAlive, true); client.Connect(ipAddress, port); pingServer = new Thread(new ThreadStart(delegate() { while (true) { Thread.Sleep(25000); if (Settings.IsClient && client.TcpClient.Connected) { Message reply; try { reply = client.WriteLineAndGetReply("#875120", new TimeSpan(0, 0, 0, 15, 0)); } catch (Exception) { reply = null; } if (reply == null) { var answer = MessageBox.Show("Kunne ikke få svar fra serveren.\nVil du vente på et svar?", "Timeout", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (answer == MessageBoxResult.No) { Application.Current.Dispatcher.Invoke(delegate() { Console.WriteLine("Disconnect"); CloseConnection(); Settings.InvokeDisconnection(false); }); break; } } } else { Application.Current.Dispatcher.Invoke(delegate() { Console.WriteLine("Disconnect"); CloseConnection(); Settings.InvokeDisconnection(false); }); break; } } })); pingServer.Start(); Settings.IsClient = true; Settings.InvokeConnection(); } catch (Exception) { Settings.IsClient = false; } return(Settings.IsClient); }