C# 通过gprs从设备读取信息
我有一个GPS设备,将安装在许多卡车上。 我可以将设备配置为通过gprs向IP和端口发送数据声明“gps数据,设备id”。 我正在使用C# 通过gprs从设备读取信息,c#,tcp,gprs,C#,Tcp,Gprs,我有一个GPS设备,将安装在许多卡车上。 我可以将设备配置为通过gprs向IP和端口发送数据声明“gps数据,设备id”。 我正在使用TcpListener类读取服务器端的数据 TcpListener server = null; private void listen_data() { Int32 port = controller_port; IPAddress localAddr = IPAddress.Parse(this_ip); server = new Tc
TcpListener
类读取服务器端的数据
TcpListener server = null;
private void listen_data()
{
Int32 port = controller_port;
IPAddress localAddr = IPAddress.Parse(this_ip);
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
Console.Write("Waiting for a connection...-- ");
TcpClient client = server.AcceptTcpClient();
Console.Write("Connected!");
data = null; int i;
NetworkStream stream = client.GetStream();
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
}
}
}
该方法正在侦听服务器ip和端口上的内容
Martin在您的代码中,您正在侦听所有设备,但只有在完成从第一个设备读取所有数据后,您才会收到“请求通道在等待答复时超时”。您应该有不同的线程,每个线程处理一个
tcpClient
所以代码应该是这样的:
TcpListener server = null;
private void listen_data()
{
Int32 port = controller_port;
IPAddress localAddr = IPAddress.Parse(this_ip);
server = new TcpListener(localAddr, port);
server.Start();
while (true)
{
Console.Write("Waiting for a connection...-- ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("new client connected");
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClient), client);//or use Task if 4.0 or new Thread...
}
}
private void HandleClient(object tcpClient)
{
TcpClient client = (TcpClient)tcpClient;
Byte[] bytes = new Byte[256];
String data = null;
int i;
NetworkStream stream = client.GetStream();
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
}
Console.WriteLine(data);
}
错误1“System.Threading.ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback)”的最佳重载方法匹配项有一些无效参数,另一个错误错误Error2Argument“1”:无法从“void”转换为“System.Threading.WaitCallback”非常感谢我没有尝试,但已修复了旧的参数。非常感谢