Connecting to websocket using C# (I can connect using JavaScript, but C# gives Status code 200 error)

后端 未结 6 1895
野性不改
野性不改 2021-01-30 07:29

I am new in the area of websocket.

I can connect to websocket server using JavaScript using this code:

var webSocket = new WebSocket(url);
6条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-30 08:00

    Not quite sure what happened to WebSocketSharp nuget package, however I noticed that now WebSocket# is showing up as most relevant result in nuget repo. It took me some time before I realized that Connect() is now returning Task, hopefully this example will be useful to someone:

    using System;
    using System.Threading.Tasks;
    using WebSocketSharp;
    
    namespace Example
    {
        class Program
        {
            private static void Main(string[] args)
            {
                using (var ws = new WebSocket(url: "ws://localhost:1337", onMessage: OnMessage, onError: OnError))
                {
                    ws.Connect().Wait();
                    ws.Send("Hey, Server!").Wait();
                    Console.ReadKey(true);
                }
            }
    
            private static Task OnError(ErrorEventArgs errorEventArgs)
            {
                Console.Write("Error: {0}, Exception: {1}", errorEventArgs.Message, errorEventArgs.Exception);
                return Task.FromResult(0);
            }
    
            private static Task OnMessage(MessageEventArgs messageEventArgs)
            {
                Console.Write("Message received: {0}", messageEventArgs.Text.ReadToEnd());
                return Task.FromResult(0);
            }
        }
    }
    

提交回复
热议问题