Search code examples
c#-4.0windows-phone-8websocket

How to send/receive messages through a web socket on windows phone 8 using the class ClientWebSocket?


The web socket is written in javascript by my colleague. I managed to connect. First of all I have to log in on the application using a test account. I have to send the email and password through a json. I have installed the Json.Net packet using NuGet.

Some code that I found on my reaserch is this, but I do not understand how to send my data using that segment.

var buffer = new byte[1024];
var segment = new ArraySegment<byte>(buffer);
webSocket.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None);

Of course, I can use an object

User user=new User();
user.Email="[email protected]";
user.Password="pass";
string json = JsonConvert.SerializeObject(user);

But it will not be of any use because the method SendAsync accepts only byte type on segment.

All I want is to send that data, and if log in succeeds, I should receive other data (in Json format) about the user.

As a side note, I am quite new to web sockets, I used http protocols from ASP.NET WEB API 2.


Solution

  • I have no idea about Windows Phone 8, but by the code you pasted it seems similar to the regular .NET ClientWebSocket, so here you have some examples:

    public static Task SendString(ClientWebSocket ws, String data, CancellationToken cancellation)
    {
        var encoded = Encoding.UTF8.GetBytes(data);
        var buffer = new ArraySegment<Byte>(encoded, 0, encoded.Length);
        return ws.SendAsync(buffer, WebSocketMessageType.Text, true, cancellation);
    }
    
    public static async Task<String> ReadString(ClientWebSocket ws)
    {
        ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);
    
        WebSocketReceiveResult result = null;
    
        using (var ms = new MemoryStream())
        {
            do
            {
                result = await ws.ReceiveAsync(buffer, CancellationToken.None);
                ms.Write(buffer.Array, buffer.Offset, result.Count);
            }
            while (!result.EndOfMessage);
    
            ms.Seek(0, SeekOrigin.Begin);
    
            using (var reader = new StreamReader(ms, Encoding.UTF8))
                return reader.ReadToEnd();
        }
    }
    

    If something does not compile or exists in WP8, just find an equivalent.