0

I am trying to communicate with echo service on a server using web sockets in my bot. I am using WebSocketSharp assembly to create web socket connection. I want to echo back whatever user types in the bot but, it never fires "ws.OnMessage" event and I get back no response. I tested the connection on the console application and every thing works fine there. Please suggest what I am doing wrong here.

Following is my MessageController

public 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;
    }

Following is my HumanCollaboratorDialog class

[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;

        using (var ws = new WebSocket("ws://Some IP addrress:8080/human-collaborator/echo"))
        {

            ws.OnMessage += async (sender, e) =>
            {
                try
                {
                    await context.PostAsync(e.Data);
                }
                catch (Exception ex)
                {
                    await context.PostAsync($"Exception: {ex.Message}");
                }
            };

            ws.ConnectAsync();
            var msg = message.Text;
            ws.Send(msg);

        }

        context.Wait(this.MessageReceivedAsync);
    }
}
Ehsan Ul Haq
  • 209
  • 3
  • 12

1 Answers1

0

The "MessageReceivedAsync" is not the correct place to create a websocket. WebSockets in the bot framework are used for receiving messages in a Direct Line connection scenario. A StreamUrl obtained from a call to StartConversationAsync is used to create the web socket:

var token = await new DirectLineClient(dlSecret).Tokens.GenerateTokenForNewConversationAsync();

// Use token to create conversation
var directLineClient = new DirectLineClient(tokenResponse.Token);
var conversation = await directLineClient.Conversations.StartConversationAsync();

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

etc.

Please see here: https://github.com/Microsoft/BotBuilder-Samples/blob/master/CSharp/core-DirectLineWebSockets/DirectLineClient/Program.cs

Ezequiel Jadib
  • 14,767
  • 2
  • 38
  • 43
Eric Dahlvang
  • 8,252
  • 4
  • 29
  • 50