Xamarin.ios Web Socket with Rails cable

Image for post
Image for post

What is web socket?

What is Rails cable?

rails new websocket
Image for post
Image for post
class ChatsChannel < ApplicationCable::Channel  def subscribed 
stream_from “chat”
end
end
Rails.application.routes.draw do mount ActionCable.server => ‘/cable’end
config.action_cable.url = ‘ws://192.168.8.104:3000/cable’
config.action_cable.allowed_request_origins = [ ‘ws://192.168.8.104:3000’,’http://192.168.8.104:3000' ]
Image for post
Image for post
Image for post
Image for post
using System;
using WebSocket4Net;
using UIKit;namespace SocketApp{
public partial class ViewController : UIViewController
{
WebSocket websocket = new WebSocket(“ws://192.168.8.104:3000/cable”);
protected ViewController(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
}
}
}
public override void ViewDidLoad()
{
websocket.Opened += new EventHandler(websocket_Opened);
websocket.Error += new EventHandler<ErrorEventArgs>(websocket_Error);
websocket.Closed += new EventHandler(websocket_Closed);
websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived);
base.ViewDidLoad();
}
private void websocket_Error(object sender, ErrorEventArgs e)
{
}
private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
}
private void websocket_Closed(object sender, EventArgs e)
{
}
private void websocket_Opened(object sender, EventArgs e)
{
}
 private void websocket_Opened(object sender, EventArgs e)
{
Dictionary<string, string> dictionary =
new Dictionary<string, string>();
dictionary.Add(“command”, “subscribe”);
dictionary.Add(“identifier”, “{“channel”: “UsersChannel”}”);
var j = JsonConvert.SerializeObject(dictionary); websocket.Send(j);
}
private void websocket_Opened(object sender, EventArgs e)
{
JObject o = JObject.Parse(e.Message.ToString());
if (o[“type”] == null)
{
InvokeOnMainThread(() =>
{
textView.Text = textView.Text + “\n” + e.Message;
});
}
}
partial void tapMessage(UIButton sender)
{
Dictionary<string, string> dictionary =
new Dictionary<string, string>();
dictionary.Add(“command”, “message”);
dictionary.Add(“identifier”, “{“channel”: “UsersChannel”}”);
dictionary.Add(“data”, “{“action”:”chat_message”,”msg”: “ + “”” + message.Text + “”}”);
var j = JsonConvert.SerializeObject(dictionary); websocket.Send(j);
}
class ChatsChannel < ApplicationCable::Channel def subscribed
stream_from “chat”
end
def chat_message(data) ActionCable.server.broadcast “chat” , success: ‘yes’, msg: data[‘msg’] endend

A Software architect

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store