2012-08-13 101 views
1

我在哪里工作,我们目前使用的时钟输入系统使用连接到我们网络的手持扫描器。我想知道是否有通过C#的方式连接到此设备并从此设备接收任何输入。或者,就此而言,以类似的方式连接任何其他输入设备。如果有的话,如果有人能给我一些指点,让我开始,或建议去哪里看。从TCP/IP设备接收数据

+0

综观API文档中的设备会成为最好的地方...我们不能告诉你。在最基本的层面上,'Socket','NetworkStream'和'TcpClient'可能很有用 - 但很难说不知道API。 – 2012-08-13 08:35:51

+0

是否可以连接到设备取决于设备本身。它是否带有任何文档? – CodeCaster 2012-08-13 08:36:27

+0

同意,你可能需要一个协议文件或equivilent,除非你想花很长时间猜测。 – KingCronus 2012-08-13 08:36:41

回答

1

如果任何人都可以给我一些指示,让我开始,或去哪里看。

我会建议你看看“System.Net”命名空间。使用StreamReader,StreamWriter或我推荐的NetworkStream,您可以轻松地在多个设备之间写入和读取流。

查看以下示例以了解如何托管数据并连接到主机以接收数据。

托管数据(服务器):

static string ReadData(NetworkStream network) 
{ 
    string Output = string.Empty; 
    byte[] bReads = new byte[1024]; 
    int ReadAmount = 0; 

    while (network.DataAvailable) 
    { 
     ReadAmount = network.Read(bReads, 0, bReads.Length); 
     Output += string.Format("{0}", Encoding.UTF8.GetString(
      bReads, 0, ReadAmount)); 
    } 
    return Output; 
} 

static void WriteData(NetworkStream stream, string cmd) 
{ 
    stream.Write(Encoding.UTF8.GetBytes(cmd), 0, 
    Encoding.UTF8.GetBytes(cmd).Length); 
} 

static void Main(string[] args) 
{ 
    List<TcpClient> clients = new List<TcpClient>(); 
    TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, 1337)); 
    //listener.ExclusiveAddressUse = true; // One client only? 
    listener.Start(); 
    Console.WriteLine("Server booted"); 

    Func<TcpClient, bool> SendMessage = (TcpClient client) => { 
     WriteData(client.GetStream(), "Responeded to client"); 
     return true; 
    }; 

    while (true) 
    { 
     if (listener.Pending()) { 
      clients.Add(listener.AcceptTcpClient()); 
     } 

     foreach (TcpClient client in clients) { 
      if (ReadData(client.GetStream()) != string.Empty) { 
       Console.WriteLine("Request from client"); 
       SendMessage(client); 
      } 
     } 
    } 
} 

现在客户将然后使用下面的方法来发送请求:

static string ReadData(NetworkStream network) 
{ 
    string Output = string.Empty; 
    byte[] bReads = new byte[1024]; 
    int ReadAmount = 0; 

    while (network.DataAvailable) 
    { 
     ReadAmount = network.Read(bReads, 0, bReads.Length); 

     Output += string.Format("{0}", Encoding.UTF8.GetString(
       bReads, 0, ReadAmount)); 
    } 
    return Output; 
} 

static void WriteData(NetworkStream stream, string cmd) 
{ 
    stream.Write(Encoding.UTF8.GetBytes(cmd), 0, 
       Encoding.UTF8.GetBytes(cmd).Length); 
} 

static void Main(string[] args) 
{ 
    TcpClient client = new TcpClient(); 
    client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1337)); 
    while (!client.Connected) { } // Wait for connection 

    WriteData(client.GetStream(), "Send to server"); 
    while (true) { 
     NetworkStream strm = client.GetStream(); 
     if (ReadData(strm) != string.Empty) { 
      Console.WriteLine("Recieved data from server."); 
     } 
    } 
} 
相关问题