我想用我的機器人網絡套接字與服務器通信。但是在運行時它會拋出System.NullReferenceException異常。我在不同的線程中運行套接字,以便它不會干擾機器人。套接字,空引用異常
我正在使用WebsocketSharp庫。
第一條消息進來很好,但第二條消息在HumanCollaboratorDialog類的以下行中引發異常。
await context.PostAsync(e.Data);
我的Socket流類是如下:
public static class SocketStream
{
public static WebSocket ws;
private static List<string> serverMsg = new List<string>();
public static void initializeSocket()
{
ws = new WebSocket("ws://Some IP:8080/human-collaborator/data");
Debug.WriteLine("****** INITIALIZED SOCKET (should happen only once) *****");
Task.Run(() => startSocketStream());
}
private static void startSocketStream()
{
int attempts = 0;
while (!ws.IsAlive)
{
try
{
attempts++;
ws.Connect();
}
catch (WebSocketException)
{
Debug.WriteLine("Connection attempts: " + attempts.ToString());
}
}
ws.OnOpen += (sender, args) =>
{
Debug.WriteLine("# SOCKET OPENED");
};
ws.OnError += (sender, args) =>
{
Debug.WriteLine("# SOME ERROR OCCURED");
};
ws.OnClose += (sender, args) =>
{
Debug.WriteLine("# SOCKET CLOSED");
};
}
}
我打電話Global.asx的initializeSocket()方法的應用水平
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
SocketStream.initializeSocket();
}
}
我HumanCollaboratorDialog類中運行如下:
[Serializable]
public class HumanCollaboratorDialog : IDialog<object>
{
public async Task StartAsync(IDialogContext context)
{
context.Wait(this.MessageReceivedAsync);
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
SocketStream.ws.OnMessage += async (sender, e) =>
{
try
{
await context.PostAsync(e.Data);
}
catch (HttpRequestException ex)
{
throw ex;
}
};
Thread.Sleep(500);
string output = message.Text;
SocketStream.ws.Send(output);
Thread.Sleep(500);
context.Wait(MessageReceivedAsync);
}
}
我MessagesController有以下POST方法:
public virtual async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
await Conversation.SendAsync(activity,() => new HumanCollaboratorDialog());
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
Neithet e.Data也不環境是空的。我認爲問題是與套接字連接或可能是我在做SocketStream類中的錯誤。以下是圖像
我不知道你爲什麼在Web API中運行套接字... –
@EzequielJadib我想在後臺連續運行套接字,以便在服務器上發生某些變化時它可以通知機器人。在這種情況下更好的解決方案是什麼? –
在旁註中,不要做'catch(Exception ex){throw ex; }'。 [它是邪惡的](http://stackoverflow.com/questions/881473/why-catch-and-rethrow-an-exception-in-c) – Default