如何使用C#中的Web套接字从服务器发送响应消息? [英] How to send response messages from a server using web socket in C#?

查看:90
本文介绍了如何使用C#中的Web套接字从服务器发送响应消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在c#中使用Web套接字从服务器发送响应消息。但我得到如下例外:

对象引用问题。



从客户端到服务器我可以使用客户端Web套接字发送消息。但是从服务器我无法从客户端发送消息。



I want to send response messages from a server using web socket in c#. But am getting the exception as below:
Object reference issue.

From client to server i am able to send message using client web socket. But from server I am unable to send the message from client.

But  am getting the exception as below: 
Object reference issue. 





我的尝试:



客户端和服务器发送消息的核心代码

客户端级别:



What I have tried:

Core Code of Client and Server sending messages
Client Level:

if (webSocket.State == WebSocketState.Open)
                  {
                  //Console.WriteLine("Write some to send over to server..");
                  //string stringtoSend = Console.ReadLine();
                  string stringtoSend = txtOutgoing.Text;

                  byte[] buffer = encoding.GetBytes(stringtoSend);

                  await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Binary, false, CancellationToken.None);
                  // Console.WriteLine("Sent:     " + stringtoSend);


                  await Task.Delay(1000);
              }





服务器级别:



Server level:

WebSocketContext webSocketContext = null;
            try
            {
                // while (webSocket.State == WebSocketState.Open)
                WebSocket webSocket = webSocketContext.WebSocket;

                //Console.WriteLine("Write some to send over to server..");
                //string stringtoSend = Console.ReadLine();
                string stringtoSend = txtOutgoing.Text;

                byte[] buffer = encoding.GetBytes(stringtoSend);

                await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Binary, false, CancellationToken.None);

            }
            catch (Exception ex)
            {

            }

推荐答案

抱歉重新发布。这里的情况是服务器响应即将到来,但只有在发送客户端消息后第二次发送服务器响应即将到来。因此张贴在同一个。
sorry for the repost. Here the case is the server response is coming but only after sending the client message send second time around server response coming. Hence posted on the same.


这篇关于如何使用C#中的Web套接字从服务器发送响应消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆