c# - 套接字,Nullreference异常

标签 c# .net sockets botframework websocket-sharp

我正在尝试将bot与我的机器人一起使用Web套接字与服务器进行通信。但是在运行时,它将引发System.NullReferenceException。我在后台在另一个线程上运行套接字,以便它不会与机器人冲突。

我正在使用WebsocketSharp库。

第一条消息很好,但是第二条消息在HumanCollaboratorDialog类的下一行抛出异常。

await  context.PostAsync(e.Data);

我的套接字流类如下:
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;
    }

e.Data或上下文都不为空。我认为问题出在套接字连接上,或者可能是我在SocketStream类中做错了什么。以下是图片

enter image description here

最佳答案

您的漫游器是一种网络服务。消息由客户端(网页,应用程序,另一个服务等)发送到服务,并在MessagesController的Post方法中接收。您无需为要执行的操作在服务器上插入套接字代码。 Web套接字对于通过直接线路连接从机器人接收客户端上的消息很有用。

这是使用Bot Framework的Direct Line Client并创建Web套接字连接的示例。注意如何从对话的StreamUrl创建Web套接字:

DirectLineClientCredentials creds = new DirectLineClientCredentials(directLineSecret);
DirectLineClient directLineClient = new DirectLineClient(creds);
Conversation conversation = await directLineClient.Conversations.StartConversationAsync();

using (var webSocketClient = new WebSocket(conversation.StreamUrl))
{
    webSocketClient.OnMessage += WebSocketClient_OnMessage;
    webSocketClient.Connect();
    while (true)

    {
        string input = Console.ReadLine().Trim();

        if (input.ToLower() == "exit")
        {
            break;
        }
        else
        {
            if (input.Length > 0)
            {
                Activity userMessage = new Activity
                {
                    From = new ChannelAccount(fromUser),
                    Text = input,
                    Type = ActivityTypes.Message
                };

                await directLineClient.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);
            }
        }
    }
}
private static void WebSocketClient_OnMessage(object sender, MessageEventArgs e)
{
    // avoid null reference exception when no data received
    if (string.IsNullOrWhiteSpace(e.Data))
    {
        return;
    }

    var activitySet = JsonConvert.DeserializeObject<ActivitySet>(e.Data);
    var activities = from x in activitySet.Activities
                        where x.From.Id == botId
                        select x;

    foreach (Activity activity in activities)
    {
        Console.WriteLine(activity.Text);
    }
}

这是来自控制台应用程序,该应用程序使用Direct Line与Bot进行通信,并在此处使用Web套接字监听消息:
https://github.com/Microsoft/BotBuilder-Samples/tree/master/CSharp/core-DirectLineWebSockets

关于c# - 套接字,Nullreference异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43330615/

相关文章:

c# - 如何在 abpfeature 表中添加和使用新列并在样板中访问它?

c# - 如何发送带有html附件的邮件

c# - 使用 C# SDK 投影到另一种类型

python-3.x - 如何正确关闭正在流式传输网络摄像头镜头的套接字?

c# - 如何在 Mono IDE 中使用 C# 设置命令行参数。

c# - 在 C# 中读取 .DXF/.DWG 文件

c# - 如何在 XAML 中创建类的实例?

c# - ASP.NET MVC(域模型、存储库、Fluent、服务——我项目的结构)

c++ - boost::dynamic_bitset 如何存储位

java - 如何使用 Socket 从 Android 向 Windows 中的 python 应用程序发送消息