private void listen() { listener.Start(); try { while (true) { TcpClient tcpClient = listener.AcceptTcpClient(); Client client = ClientManager.addClient(tcpClient); InformationMessage.show("client connected with endpoint: " + client.TcpClient.Client.RemoteEndPoint.ToString()); Thread receiveThread = new Thread(receive); receiveThread.Start(client); } } catch (ThreadAbortException e) { ErrorMessage.show("listen thread aborting, exception was:\r\n" + e.ToString()); } catch (SocketException e) { ErrorMessage.show("SocketException in listen thread, maybe the socket shut down, exception was:\r\n" + e.ToString()); } finally { listener.Stop(); DebugMessage.show("exiting listen thread"); } }
private void stop() { InformationMessage.show("stopping listener"); listener.Stop(); InformationMessage.show("stopping sender"); sendThread.Abort(); InformationMessage.show("stopping receivers"); ClientManager.removeAllClients(); }
private void receive(object threadArgs) { Client client = (Client)threadArgs; TcpClient tcpClient = client.TcpClient; NetworkStream clientStream = tcpClient.GetStream(); string endpointAddress = tcpClient.Client.RemoteEndPoint.ToString(); byte[] received = new byte[4096]; int bytesRead; try { while (true) { bytesRead = clientStream.Read(received, 0, received.Length); if (bytesRead == 0) { break; } InformationMessage.show("received message from: " + endpointAddress); DebugMessage.show("message length: " + bytesRead.ToString()); byte[] message = new byte[bytesRead]; Array.Copy(received, message, bytesRead); msgQueue.Enqueue(Interpreter.interpret(message, client)); newData.Set(); } } catch (ThreadAbortException e) { ErrorMessage.show("receive thread aborting, exception was:\r\n" + e.ToString()); } catch (IOException e) { ErrorMessage.show("IOException in receive thread, maybe the socket shut down, exception was:\r\n" + e.ToString()); } catch (ObjectDisposedException e) { ErrorMessage.show("ObjectDisposedException in receive thread, maybe the socket shut down, exception was:\r\n" + e.ToString()); } finally { ClientManager.removeClient(client); InformationMessage.show("client " + endpointAddress + " disconnected, closing thread"); } }
static void Main(string[] args) { Server server = new Server(); InformationMessage.show("server created"); server.start(); InformationMessage.show("server started"); String input = ""; while (input != "exit") { input = Console.ReadLine(); } server.stop(); Thread.Sleep(1000); InformationMessage.show("press any key to continue..."); Console.ReadLine(); }
private void start() { listenThread.Start(); sendThread.Start(); InformationMessage.show("server running on port " + port); }