当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Windows 10 Universal App - Socket connection recurrent readings

问题描述:

I am following the Socket Example about StreamSockets. I can read from the server as a client. The example is https://social.msdn.microsoft.com/Forums/es-ES/79eda064-473d-4398-8fe3-72369e686c3c/comunicacion-tcpcip-con-streamsocket-y-datawriterdatareader?forum=esdevwindows

I'm building a Windows 10 Universal Application and I need continuous readings from a socket connection. I'm getting the first reading but then only empty strings.

Thanks!

Image capture response

 Private StreamSocket socketForServer;

Private DataWriter cfaStreamWriter;

Private DataReader cfaStreamReader;

// Read socket data

Private Async void ReadData()

{

If (socketForServer == null) Then Return;

uint s = await cfaStreamReader.LoadAsync(1024);

String Data = cfaStreamReader.ReadString(s);

PrintData(Data);

var ignore = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () >=

ReadData());

}

// Connect to the bid controller through TCP Socket.

Public Async Task<bool> Connect()

{

socketForServer = New StreamSocket();

var hostname = New HostName(deviceSPACS_IP);

await socketForServer.ConnectAsync(hostname, deviceSPACS_PORT.ToString());

// send login

SendRawMessage("WELCOME TO SERVER");

cfaStreamReader = New DataReader(socketForServer.InputStream)

{

InputStreamOptions = InputStreamOptions.Partial

};

ReadData();

Return True;

}

// Disconnect from bid Controller

Public bool Disconnect()

{

If (socketForServer == null) Then Return False;

SendRawMessage("GOOD BYE AL SERVER");

cfaStreamReader.Dispose();

cfaStreamReader = null;

socketForServer.Dispose();

socketForServer = null;

Return True;

}

Private Async void SendRawMessage(String message)

{

cfaStreamWriter = New DataWriter(socketForServer.OutputStream); cfaStreamWriter.WriteString(message + "\r\n");

await cfaStreamWriter.StoreAsync();

await cfaStreamWriter.FlushAsync();

cfaStreamWriter.DetachStream();

cfaStreamWriter.Dispose();

cfaStreamWriter = null;

}

分享给朋友:
您可能感兴趣的文章:
随机阅读: