// // Very simple server for remote access to serial ports // serial port config is 9600bps, no parity, 8bits, 1 stop bit, no handshaking // hklab.net/wiki/Remote_access_to_serial_port // using System; using System.Net.Sockets; using System.Collections.Generic; using System.Text; using System.IO.Ports; using System.Threading; class server_rs232 { private static TcpListener server = null; private static TcpClient client = null; private static NetworkStream stream = null; private static SerialPort serial = null; // Loop to read octets from serial port and send them to network private static void ListenSerial() { byte c; for(;;) { c = (byte) serial.ReadByte(); if (client != null) if (client.Connected) { stream.WriteByte(c); Console.WriteLine("serial-->client {0}", c); } } } static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: server_rs232 "); Environment.Exit(0); } try { // serial port standart configuration serial = new SerialPort(args[1]); serial.BaudRate = 9600; serial.DataBits = 8; serial.Parity = Parity.None; serial.StopBits = StopBits.One; serial.Handshake = Handshake.None; serial.Open(); // Launch thread that reads serial port and send bytes read to the client Thread th = new Thread(ListenSerial); th.Start(); // Start listening for client requests. Int16 port = Convert.ToInt16(args[0]); server = new TcpListener(System.Net.IPAddress.Any, port); server.Start(); // Enter the listening loop while (true) { Console.WriteLine("Using serial port {0}", args[1]); Console.WriteLine("Waiting for a connection on port tcp/{0}... ", port); // Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. client = server.AcceptTcpClient(); Console.WriteLine("Connected!"); // Get a stream object for reading and writing stream = client.GetStream(); // Loop to receive all the octets sent by the client byte[] c = new byte[1]; while ((stream.Read(c, 0, 1)) != 0) { Console.WriteLine("client-->serial {0}", c[0]); serial.Write(c, 0, 1); } // Shutdown and end connection client.Close(); } } catch (System.Exception e) { Console.WriteLine("Error: {0}", e.Message); Environment.Exit(1); } finally { // Stop listening for new clients. server.Stop(); // Close serial port serial.Close(); Console.WriteLine("\nFinished."); } } }