none
WebSocket Client in JavaScript RRS feed

  • Question

  • We have a confusion in using web socket client in JavaScript. We’re able to establish the connection between WCF full duplex service and Web Socket client. We have a couple of question which bothering us and we can’t find the solution online. Hope someone can help us. Also, if anyone can recommend a good reference book for this topic then it’ll be appreciated.

    Questions:

    1. After connection is establish how to keep connection alive while we can communicate with different WCF method?
    2. How to reference different WCF method from javascript. For example we have SendMessageToClient1 and SendMessageToClient2 method then how should we reference in my JavaScript?
    3. We want to pass JSON data and return data in JSON format?

    Below is the working WCF with JavaScript:

    public class WSChatService : IHellowService 
    {
        public void SendMessageToServer1(Message msg)
        {
            var callback = OperationContext.Current.GetCallbackChannel<IHelloCallback>();
            if (msg.IsEmpty || ((IChannel)callback).State != CommunicationState.Opened)
            {
                return;
            }
    
            byte[] body = msg.GetBody<byte[]>();
            string msgTextFromClient = Encoding.UTF8.GetString(body);
    
            string msgTextToClient = string.Format(
                "Got message {0} at {1}",
                msgTextFromClient,
                DateTime.Now.ToLongTimeString());
    
            callback.SendMessageToClient1(CreateMessage(msgTextToClient));
        }
    
        private Message CreateMessage(string msgText)
        {
            Message msg = ByteStreamMessage.CreateMessage(
                new ArraySegment<byte>(Encoding.UTF8.GetBytes(msgText)));
            msg.Properties["WebSocketMessageProperty"] =
                new WebSocketMessageProperty { MessageType = WebSocketMessageType.Text };
            return msg;
        }
    }
    
    <script type="text/javascript" src="Scripts/jquery-2.0.2.js"></script>
    <script type="text/javascript">
        var ws;
        $().ready(function () {
            $("#btnConnect").click(function () {
    
                $("#spanStatus").text("connecting");
    
                //http://localhost/WcfWSChatForWeb/WSChatService.svc
                //ws = new WebSocket("ws://" + window.location.hostname + "/WcfWSChatForWeb/WSChatService.svc");
                //ws = new WebSocket("ws://192.168.100.214/WcfWSChatForWeb/WSChatService.svc");
                ws = new WebSocket("ws://localhost/WcfWSChatForWeb/WSChatService.svc");
                ws.onopen = function () {
                    $("#spanStatus").text("connected");
                };
                ws.onmessage = function (evt) {
                    $("#spanStatus").text(evt.data);
                    alert(JSON.stringify(evt.data));
                };
                ws.onerror = function (evt) {
                    $("#spanStatus").text(evt.message);
                };
                ws.onclose = function () {
                    $("#spanStatus").text("disconnected");
                };
            });
    
            $("#btnSend").click(function () {
                if (ws.readyState == WebSocket.OPEN) {
                    ws.send($("#textInput").val());
                }
                else {
                    $("#spanStatus").text("Connection is closed");
                }
            });
            $("#btnDisconnect").click(function () {
                ws.close();
            });
        });
    </script>

    Thanks for the help!


    Rushabh

    Wednesday, August 19, 2015 3:24 PM

Answers

  • Hi ShahRushabh,

    According to this case, for first problem may be we can set sendTimeOut in our web.config file to

    extend session time like below.

    <bindings>
          <netHttpBinding>
            <binding openTimeout="00:10:00" 
                     closeTimeout="00:10:00" 
                     sendTimeout="00:30:00" 
                     receiveTimeout="00:10:00">
            </binding>
          </netHttpBinding>
        </bindings>
    

    For this issue >>We want to pass JSON data and return data in JSON format?

    In my opinion is that, if you pass json data, you need to convert json data type as string or other type

    in javascript. And you want to return json data, you also need to convert string type to json type.

    Because you used nethttpbinding, so it  messageEncoding mode just support Binary/Text/Mtom.

    For more information, please refer to the following articles:

    1.JSON.parse Function (JavaScript)

    I hope that will be helpful to you.

    Best Regards,

    Grady

    • Marked as answer by ShahRushabh Thursday, August 20, 2015 7:37 PM
    Thursday, August 20, 2015 11:58 AM
    Moderator