如何简单地实现将COM端口通过TCP共享给多个客户端的设计模式?
例如,一个本地GPS设备可以在实时情况下向远程主机传输坐标。
因此,我需要一个程序,它会打开串口并接受多个TCP连接,例如:
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);
}
}
}
我需要一个类来处理连接客户端之间的通信,使它们都能看到数据并保持同步,以便客户端命令按顺序接收:
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();
}
}
}
我正在努力解决的问题是如何促进SerialPort实例和线程之间的通信。
我不确定上面的代码是否是最好的解决方案,所以是否有其他解决方案(越简单越好)?