我想创建一个UWP客户端套接字。我使用StreamSocket,但尝试连接它时出现错误。
换句话说,当代码到达await ConnectSocket(IP, PORT)
时,将引发以下异常:
我不明白以下异常:
任务被取消。 在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task 任务) 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task 任务) 在System.Runtime.CompilerServices.TaskAwaiter.GetResult() 在BluetoothLEExplorer.Models.SocketWriter.d__7.MoveNext()
System.Collections.ListDictionaryInternal
这是我的套接字类的代码:
public class SocketWriter
{
private StreamSocket socket = null;
public StreamSocket Socket
{
get
{
return this.socket;
}
}
private String errorMessage;
public async Task<Boolean> ConnectSocket(string host, string port)
{
try
{
socket = new StreamSocket();
socket.Control.KeepAlive = true;
HostName hostName = new HostName(host);
await socket.ConnectAsync(hostName, port);
return true;
}
catch (Exception ex)
{
return false;
}
}
public async Task<Boolean> Send(string message)
{
try
{
Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
await writer.WriteLineAsync(message);
await writer.FlushAsync();
return true;
}
catch (Exception ex)
{
StopSocket();
return false;
}
}
public Boolean StopSocket()
{
try
{
socket.Dispose();
socket = null;
return true;
}
catch (Exception ex)
{
return false;
}
}
}
为什么我有这个异常,如何纠正呢?