Answer the question
In order to leave comments, you need to log in
How to implement a WebSocket client using standard Xamarin tools?
Hello.
Began to deal with the Xamarin Studio environment. I set myself the goal of writing a simple WebSocket client for Android . It's good to see the documentation .
The information is there, so you can google it. It seems to have googled examples for pure c#, for example:
Answer the question
In order to leave comments, you need to log in
I don't have Xamarin installed right now, so this is a console example, but I'm 99.9% sure it will work there too. The example is purely for demonstration, there is both a server and a client at once.
using System;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
ServerLaunchAsync();
ClientLaunchAsync();
Console.ReadKey();
}
private static async void ServerLaunchAsync()
{
var httpListener = new HttpListener();
httpListener.Prefixes.Add("http://localhost:5000/");
httpListener.Start();
HttpListenerContext listenerContext = await httpListener.GetContextAsync();
if (listenerContext.Request.IsWebSocketRequest)
{
WebSocketContext webSocketContext = await listenerContext.AcceptWebSocketAsync(null);
WebSocket webSocket = webSocketContext.WebSocket;
// Do something with WebSocket
var buffer = new byte[1000];
var segment = new ArraySegment<byte>(buffer);
var result = await webSocket.ReceiveAsync(segment, CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(segment.Array));
}
else
{
listenerContext.Response.StatusCode = 426;
listenerContext.Response.Close();
}
}
private static async void ClientLaunchAsync()
{
ClientWebSocket webSocket = null;
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri("ws://localhost:5000"), CancellationToken.None);
// Do something with WebSocket
var arraySegment = new ArraySegment<byte>(Encoding.UTF8.GetBytes("Hello"));
await webSocket.SendAsync(arraySegment, WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question