//Thread erzeugen bei neuer Verbindung private void ListenForClients() { this.tcpListener.Start(); while (true) { //blocks until a client has connected to the server TcpClient client = this.tcpListener.AcceptTcpClient(); AppendToRichEditControl("Neu verbunden: "+client.Client.RemoteEndPoint.ToString()+"\r" ); //create a thread to handle communication //with connected client Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm)); clientThread.Start(client); } } //Messages bearbeiten private void HandleClientComm(object client) { TcpClient tcpClient = (TcpClient)client; NetworkStream clientStream = tcpClient.GetStream(); //todo stürzt ab beim vorzeitigen abschalten der CNC byte[] message = new byte[4096]; int bytesRead; int sizeToGet; int cncId=0; Type_t type; Command_t command; while (true) { bytesRead = 0; try { //blocks until a client sends a message bytesRead = clientStream.Read(message, 0, 4096); } catch { //a socket error has occured AppendToRichEditControl("Station: " + cncId + " wg. SocketFehler nicht mehr verbunden\r"); break; } if (bytesRead == 0) { //the client has disconnected from the server AppendToRichEditControl("Station: " + cncId + " nicht mehr verbunden\r"); break; } try { if (bytesRead >= 4) { type = (Type_t)message[0]; command = (Command_t)message[1]; sizeToGet = message[2] * 128 + message[3]; switch (command) { case Command_t.command_getProgramm: if (File.Exists(filenameRoot + "programm.dat")) { FileStream fileStream = new FileStream(filenameRoot + "programm.dat", FileMode.Open, FileAccess.Read); int length = (int)fileStream.Length; int totalLength = length + 5; byte[] outData; int totalLength = 5; int length = 0; outData = new byte[totalLength]; //1 byte mehr wegen ok in byte 5 outData[0] = (byte)Type_t.type_serverAnswer; outData[1] = (byte)command; outData[2] = (byte)((length+1) / 128); //das Antwortbyte 4 braucht Platz outData[3] = (byte)((length+1) % 128); outData[4] = (byte)0; //das ist dann ok //DAten aus Datei holen fileStream.Read(outData, 5, length); //Header + Daten ausgeben clientStream.Write(outData, 0, totalLength); //todo stimmt hier sum clientStream.Flush(); } else { //Fehlermeldung 2 erzeugen byte[] outData; outData = new byte[5]; //1 byte mehr wegen ok in byte 5 outData[0] = (byte)Type_t.type_serverAnswer; outData[1] = (byte)command; outData[2] = (byte)(5 / 128); outData[3] = (byte)(5 % 128); outData[4] = (byte)2; //das ist dann Fehler 2 clientStream.Write(outData, 0, 5); //todo stimmt hier sum clientStream.Flush(); } break; } } } catch (Exception e) { MessageBox.Show("Ende wegen Fehler: " + e.ToString()); tcpClient.Close(); break; } //message has successfully been received ASCIIEncoding encoder = new ASCIIEncoding(); System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead)); //clientStream.Write(message,0,bytesRead); } tcpClient.Close(); }