【发布时间】:2017-09-20 00:25:29
【问题描述】:
我编写了一个 TCP 服务器应用程序,我可以在其中侦听专用端口上的传入连接。有了这个,我可以得到一个“连接”事件,然后接收数据(只有一次)。
如何从端口连续接收数据(也许还可以检测客户端是否仍然连接)?
我连接了一个 NodeMCU(基于 Arduino)系统,该系统使用 TCP 连接每秒发送一些温度数据。
通过 UI 中的切换开关启动和停止服务器:
public async Task<bool> StartListeningAsync()
{
if (TCPSocket == null)
{
TCPSocket = new StreamSocketListener();
TCPSocket.ConnectionReceived += LocalSocketConnectionReceived;
await TCPSocket.BindServiceNameAsync(CommunicationPort);
return true;
}
return false;
}
public async Task<bool> StopListening()
{
if (connectedSocket != null)
{
connectedSocket.Dispose();
connectedSocket = null;
}
if (TCPSocket != null)
{
await TCPSocket.CancelIOAsync();
TCPSocket.ConnectionReceived -= LocalSocketConnectionReceived;
TCPSocket.Dispose();
TCPSocket = null;
return true;
}
return false;
}
处理新连接并接收数据的事件:
private async void LocalSocketConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
if (connectedSocket != null)
{
connectedSocket.Dispose();
connectedSocket = null;
}
connectedSocket = args.Socket;
await textBox_send.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
textBox_send.IsEnabled = true;
txtConnected.Text = "Client Connected";
});
using (var reader = new DataReader(args.Socket.InputStream))
{
await readTCPDataAsync(reader);
}
}
private async Task readTCPDataAsync(DataReader reader)
{
reader.InputStreamOptions = InputStreamOptions.None;
// Read the length of the payload that will be received.
byte[] payloadSize = new byte[(uint)BitConverter.GetBytes(0).Length];
await reader.LoadAsync((uint)payloadSize.Length);
reader.ReadBytes(payloadSize);
// Read the payload.
int size = BitConverter.ToInt32(payloadSize, 0);
//size = 2;
byte[] payload = new byte[size];
await reader.LoadAsync((uint)size);
reader.ReadBytes(payload);
string data = Encoding.ASCII.GetString(payload);
}
一旦建立连接,此代码可以完美地接收数据。
我正在考虑一种解决方案,一旦新数据在输入缓冲区中就获取事件,然后处理数据。
【问题讨论】: