Sharing a COM port over TCP

Posted by guinness on Stack Overflow See other posts from Stack Overflow or by guinness
Published on 2010-04-07T05:38:01Z Indexed on 2010/04/07 5:43 UTC
Read the original article Hit count: 255

Filed under:

What would be a simple design pattern for sharing a COM port over TCP to multiple clients?

For example, a local GPS device that could transmit co-ordinates to remote hosts in realtime.

So I need a program that would open the serial port and accept multiple TCP connections like:

class Program
{
    public static void Main(string[] args)
    {
        SerialPort sp = new SerialPort("COM4", 19200, Parity.None, 8, StopBits.One); 

        Socket srv = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        srv.Bind(new IPEndPoint(IPAddress.Any, 8000));
        srv.Listen(20);

        while (true)
        {
            Socket soc = srv.Accept();
            new Connection(soc);
        }
    }
}

I would then need a class to handle the communication between connected clients, allowing them all to see the data and keeping it synchronized so client commands are received in sequence:

class Connection
{
    static object lck = new object();
    static List<Connection> cons = new List<Connection>();

    public Socket socket;
    public StreamReader reader;
    public StreamWriter writer;

    public Connection(Socket soc)
    {
        this.socket = soc;
        this.reader = new StreamReader(new NetworkStream(soc, false));
        this.writer = new StreamWriter(new NetworkStream(soc, true));
        new Thread(ClientLoop).Start();
    }

    void ClientLoop()
    {
        lock (lck)
        {
            connections.Add(this);
        }
        while (true)
        {
            lock (lck)
            {
                string line = reader.ReadLine();
                if (String.IsNullOrEmpty(line))
                    break;

                foreach (Connection con in cons)
                    con.writer.WriteLine(line);
            }
        }
        lock (lck)
        {
            cons.Remove(this);
            socket.Close();
        }
    }
}

The problem I'm struggling to resolve is how to facilitate communication between the SerialPort instance and the threads.

I'm not certain that the above code is the best way forward, so does anybody have another solution (the simpler the better)?

© Stack Overflow or respective owner

Related posts about c#