我有一个问题我尝试通过套接字从node.js服务器读取uwp应用程序中的字符串,但没有成功。我有一个System.Runtime.InteropServices.COMException,我不知道如何解决它。我设法从uwp客户端向节点服务器发送一个字符串,但我不能这样做。这是我的代码我做错了什么?
这是我的node.js服务器代码
public async Task connect()
{
try
{
HostName hostName;
hostName = new HostName(SocksParameters.Host);
socket.Control.NoDelay = false;
var cts = new CancellationTokenSource();
cts.CancelAfter(SampleConfiguration.timeout);
// Connect to the server
var connectAsync = socket.ConnectAsync(hostName, SocksParameters.Port);
var connectTask = connectAsync.AsTask(cts.Token);
await connectTask;
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
await new MessageDialog("Make sure your Server is open and make sure you follow Instructions To connect localhost").ShowAsync();
Application.Current.Exit();
}
}
public async Task<String> read()
{
DataReader reader;
StringBuilder strBuilder;
using (reader = new DataReader(socket.InputStream))
{
try
{
strBuilder = new StringBuilder();
reader.InputStreamOptions = Windows.Storage.Streams.InputStreamOptions.Partial;
reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
reader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;
await reader.LoadAsync(256);
while (reader.UnconsumedBufferLength > 0)
{
strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
await reader.LoadAsync(256);//System.Runtime.InteropServices.COMException Exception caught
}
reader.DetachStream();
return strBuilder.ToString();
}
catch (Exception e)
{
return (e.ToString());
}
}
}
这是我的UWP代码
Activated Event Time Duration Thread
Exception thrown: 'System.Runtime.InteropServices.COMException' in mscorlib.ni.dll ("The I/O operation has been aborted because of either a thread exit or an application request.
The I/O operation has been aborted because of either a thread exit or an application request.
") 0.55s [18700] <No Name>
Rails 4.1.0
答案 0 :(得分:1)
我测试了代码,我发现如果DataReader
对象reader
无法读取更多数据,代码行await reader.LoadAsync(256);
将始终等待,直到新消息从服务器和DataReader
可以读取它。在您的代码中,如果来自服务器的数据大小小于256,则第二次调用LoadAsync
方法可能会导致问题。
await reader.LoadAsync(256);
while (reader.UnconsumedBufferLength > 0)
{
strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
await reader.LoadAsync(256);
//System.Runtime.InteropServices.COMException Exception caught
}
我在这里提供的解决方法是判断是否可以读取剩余数据。更新后的代码如下:
var loadsize = await reader.LoadAsync(256);
while (loadsize >= 256)
{
loadsize = await reader.LoadAsync(256);
}
if (reader.UnconsumedBufferLength > 0)
{
strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
}
在我看来,您似乎可以使用StreamReader
,它也适用于您的方案,而不是DataReader
,因为它更简单易用。代码如下:
Stream streamIn = socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(streamIn);
string response = await reader.ReadLineAsync();
return response;
有关uwp中StreamSocket
的更多详情,请参阅official sample。