通过 TCP 将 COM 端口共享给多个客户端的简单设计模式是什么?
例如,可以将坐标实时传输到远程主机的本地 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 实例和线程之间的通信。
我不确定上面的代码是最好的方法,那么有没有人有另一种解决方案(越简单越好)?