gpt4 book ai didi

c# - 套接字,Nullreference异常

转载 作者:行者123 更新时间:2023-12-03 12:03:53 25 4
gpt4 key购买 nike

我正在尝试将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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com