{"id":33649,"date":"2017-10-09T14:17:54","date_gmt":"2017-10-09T21:17:54","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=33649"},"modified":"2019-04-04T07:48:28","modified_gmt":"2019-04-04T14:48:28","slug":"developing-real-time-communication-apps-with-websocket","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/developing-real-time-communication-apps-with-websocket\/","title":{"rendered":"Developing Real-Time Communication Apps with WebSocket"},"content":{"rendered":"<p>\t\t\t\tWebSocket is a two-way communication protocol, or persistence communication channel over TCP connection, an extremely powerful protocol leveraged by numerous games, apps with chat functionality, and real-time apps such as stock tickers.<\/p>\n<p>In this blog post, we&#8217;ll discuss how to build a simple Xamarin chat room application that will leverage and connect to an ASP.NET Core WebSocket service.<\/p>\n<h2>Getting Started with WebSocket<\/h2>\n<ol>\n<li>Download the server source code from GitHub <a href=\"https:\/\/github.com\/prashantvc\/easychat-service\/tree\/master\/service\">here<\/a>.<\/li>\n<li>Install dotnet core 2.0 on your machine to run the server. Find the instructions <a href=\"https:\/\/www.microsoft.com\/net\/download\/core\">here<\/a>.<\/li>\n<li>Run <code>dotnet run<\/code> in the terminal once you\u2019re in the source directory.<\/li>\n<li>Visit http:\/\/locahosthost:5000 or http:\/\/(IP\/Hostname):5000, and make sure you see <em>Easy chat<\/em> service message on the web page.<\/li>\n<\/ol>\n<h3>Building the Mobile Client<\/h3>\n<p>Let\u2019s start with creating a blank Xamarin.Forms app leveraging a shared project (a .NET Standard library could also be used) and call it <em>EasyChat<\/em>. We&#8217;ll use the <a href=\"https:\/\/www.nuget.org\/packages\/System.Net.WebSockets.Client\/\">System.Net.WebSockets.Client<\/a> NuGet package in our mobile apps to communicate with the server.<\/p>\n<p>Once the project is created, we can use the <em>MainPage.xaml<\/em> as a simple sign in page from which we&#8217;ll navigate to the chat room.\n<img decoding=\"async\" class=\"aligncenter  wp-image-33657\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/WebSocket_EasyChat.png\" alt=\"\" width=\"528\" height=\"516\" \/><\/p>\n<p>Next, we can add a new page for the chat room, <em>ChatPage.xaml<\/em>, and a very simple View Model called <em>ChatPageViewModel.cs<\/em> to handle WebSocket&#8217;s client-side code. Here in this view model, we have code to connect to the server and send and receive messages.<\/p>\n<h3>Connecting to a Socket<\/h3>\n<p>Using the <code>System.Net.WebSockets.ClietWebSocket<\/code> object to establish the connection, this object will be used subsequently to communicate with the server<\/p>\n<pre><code>var client = new ClientWebSocket();\n...\nasync void ConnectToServerAsync() \n{\n    await client.ConnectAsync(new Uri(\"ws:\/\/10.0.2.2:5000\"), cts.Token);\n    UpdateClientState();\n\n    await Task.Factory.StartNew(async () =&gt; \n    {\n        while (true) \n        {\n            await ReadMessage();\n        }\n    }, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);\n}<\/code><\/pre>\n<p>Notice I&#8217;m using the IP address <code>10.0.2.2<\/code> to connect to the server with the <code>ConnectAsync<\/code> method. This is the default host IP on the <strong>Android emulator<\/strong>, and we cannot use <code>localhost<\/code> or the default localhost IP.<\/p>\n<p>iOS simulator running on Mac does allow us to use <code>localhost<\/code>, but when running on an iOS\/Android device we must use hostname\/IP address.<\/p>\n<h3>Reading Messages<\/h3>\n<p>Once a connection is open with the server, we can start monitoring for the incoming messages using the <code>ReceiveAsync<\/code> method. In this scenario, the messages are UTF8 encoded byte array; when we receive the message we have to convert <code>bytes<\/code> into readable <code>string<\/code> and ignore anything that is not text<\/p>\n<pre><code>async Task ReadMessage() \n{\n    WebSocketReceiveResult result;\n    var message = new ArraySegment(new byte[4096]);\n    do \n    {\n        result = await client.ReceiveAsync(message, cts.Token);\n        if (result.MessageType != WebSocketMessageType.Text)\n            break;\n        var messageBytes = message.Skip(message.Offset).Take(result.Count).ToArray();\n        string receivedMessage = Encoding.UTF8.GetString(messageBytes);\n        Console.WriteLine(\"Received: {0}\", receivedMessage);\n    } \n    while (!result.EndOfMessage);\n}<\/code><\/pre>\n<p>&nbsp;<\/p>\n<h3>Sending Messages<\/h3>\n<p>To send a message, we first need to convert the text to a byte array (using UTF8 encoding) and call the <code>SendAsync<\/code> method. Additionally, <code>SendAsync<\/code> requires parameters to identify the message type, and if it is the end of the message.<\/p>\n<pre><code>async void SendMessageAsync(string message) \n{\n    if (!CanSendMessage(message))\n        return;\n\n    var byteMessage = Encoding.UTF8.GetBytes(message);\n    var segmnet = new ArraySegment(byteMessage);\n\n    await client.SendAsync(segmnet, WebSocketMessageType.Text, true, cts.Token);\n}<\/code><\/pre>\n<p>&nbsp;<\/p>\n<h3>Wrapping Up<\/h3>\n<p>In this post, we reviewed the necessary code to connect, receive, and send messages in real-time using Web Socket in Xamarin apps. You can explore more about the available APIs <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.net.websockets(v=vs.110).aspx\">on MSDN<\/a> and download the completed sample Xamarin.Forms application <a href=\"https:\/\/github.com\/prashantvc\/easychat-service\">on GitHub<\/a>.<\/p>\n<p><em><a href=\"https:\/\/forums.xamarin.com\/104642\/guide-to-using-websockets-in-xamarin-apps\">Discuss this post on the forums.<\/a><\/em>\t\t<\/p>\n","protected":false},"excerpt":{"rendered":"<p>WebSocket is a two-way communication protocol, or persistence communication channel over TCP connection, an extremely powerful protocol leveraged by numerous games, apps with chat functionality, and real-time apps such as stock tickers. In this blog post, we&#8217;ll discuss how to build a simple Xamarin chat room application that will leverage and connect to an ASP.NET [&hellip;]<\/p>\n","protected":false},"author":558,"featured_media":33657,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[4,16],"class_list":["post-33649","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-xamarin-platform","tag-xamarin-forms"],"acf":[],"blog_post_summary":"<p>WebSocket is a two-way communication protocol, or persistence communication channel over TCP connection, an extremely powerful protocol leveraged by numerous games, apps with chat functionality, and real-time apps such as stock tickers. In this blog post, we&#8217;ll discuss how to build a simple Xamarin chat room application that will leverage and connect to an ASP.NET [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/33649","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/users\/558"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=33649"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/33649\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=33649"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=33649"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=33649"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}