I'm using Xamarin(mono 3.2.5) on OSX to create a C# console app that connects to the blockchain.info websocket stream. I've included the socketio4net library from NuGet and thought I followed the specs correctly, but I'm a bit new to socket.io connections in general, so please correct me on what I'm doing wrong. I get an error immediately after calling the socket.Connect() method below.
I have created a few event handlers like so:
static void SocketOpened(object sender, EventArgs e)
{
Console.WriteLine ("opened event handler");
Console.WriteLine (e.ToString());
}
static void SocketError(object sender, SocketIOClient.ErrorEventArgs e)
{
Console.WriteLine ("error event handler");
Console.WriteLine (e.Message);
}
static void SocketMessage(object sender, MessageEventArgs e)
{
Console.WriteLine ("message event handler");
Console.WriteLine (e.Message);
}
and my code is as follows:
var socket = new Client (#"ws://ws.blockchain.info:8335/inv");
socket.Opened += SocketOpened;
socket.Error += SocketError;
socket.Message += SocketMessage;
socket.Connect ();
Console.WriteLine ("handshake: " + socket.HandShake.ErrorMessage);
socket.On("connect", (fn) => {
Console.WriteLine("On.connect msg: " + fn.MessageText);
});
socket.On ("open", (fn) => {
Console.WriteLine("On.open msg: " + fn.MessageText);
});
my console output from this:
error event handler
Error initializing handshake with ws://ws.blockchain.info:8335/inv
handshake: Error getting handsake from Socket.IO host instance: An error occurred performing a WebClient request.
What have I done incorrectly? The blockchain API documentation is here: https://blockchain.info/api/api_websocket and I've tried both URLs they specify. Omitting the port number in the URL generates a different error. Instead of "error performing WebClient request", it appears to hunt for a local path to the socket server, which clearly is incorrect.
Any help from a more experienced programmer would be much appreciated
I face the same problem, on my case, its because of default internet connection at office must go through proxy.
Simply set the proxy to none with the code below, solved my problem.
System.Net.WebRequest.DefaultWebProxy = null;
Related
I have a C# application that connects to a NATS service to send and accept NATS messages. It is working well for some time. However I need to build in some logic that if the NATS service is stopped that I take action in letting the user know that we can't send or receive messages. I looked at examples on the internet and applied it accordingly but when testing I see no response as if the events are not triggered. When I stop the NATS service I am expecting the event to fire and a message to be displayed. Can anyone show me what I am missing?
private void OpenNatsConnections()
{
LocalLog("Opening connection to Nats");
// Setup connection options
Options Opts = ConnectionFactory.GetDefaultOptions();
Opts.Url = appSettings.GetNatsUrl();
Opts.User = appSettings.NATSUsername;
Opts.Password = appSettings.NATSPassword;
Opts.AsyncErrorEventHandler += (sender, args) =>
{
LocalLog("AsyncErrorEventHandler");
};
Opts.ClosedEventHandler += (sender, args) =>
{
LocalLog("ClosedEventHandler");
};
Opts.DisconnectedEventHandler += (sender, args) =>
{
LocalLog("DisconnectedEventHandler");
};
// Open Nats connection, assign event handeler and subscribe to listening channel
try
{
NATSConnection = new ConnectionFactory().CreateConnection(Opts);
AsyncNATSMessageHandler = (sender, args) =>
{
string MessageData = Encoding.ASCII.GetString(args.Message.Data);
DetermineMessageType(MessageData, args.Message.Reply);
};
SubscribeToNATS();
LocalLog("Connected to Nats");
}
catch (Exception e)
{
LocalLog("Critical!! Connection to NATS failed! Error Message - " + e.Message);
}
}
I have managed to resolve the issue. Quite simple rather. I downloaded the latest version of NATS Client and the above code worked and the relevant code is fired when triggered.
I have a WinForms C# .NET 4.5.2 OWIN self hosted server that uses a signalr hub. In this same WinForm project I start the signalr hub as follows:
private void Form1_Load(object sender, EventArgs e) {
hubConnection = new HubConnection("http://localhost:12345/", clientParams);
hubProxy = hubConnection.CreateHubProxy("OfmControl");
hubProxy.On("Message", message => onData(message));
hubConnection.Start();
My onData method looks like this:
private void onData(dynamic message)
{
var file = new System.IO.FileInfo(message);
playVideo(file.FullName);
}
playVideo method looks like this:
private void playVideo(string file)
{
int tc6 = 0;
try
{
axWMPn[0].URL = file;
}
catch (System.Runtime.InteropServices.COMException comEx)
{
Console.WriteLine("playVideo COMException 0: " + comEx.Source + " -- " + comEx.Message);
}
}
axWMPn is an activex Windows Media Player object on the main form. When I run a separate C# signalr client program and send a filename message to this OWIN signalr sever and onData receives the filename and assigns it to axWMPn[0] per above code it always works never hits catch exception never receive a cross thread exception? I have run it hundreds of times never once received a cross thread exception and always works? But if I do the following I receive a cross thread exception every time obviously:
private void onData(dynamic message)
{
textBox1.text = message; ---> cross thread exception everytime here
var file = new System.IO.FileInfo(message);
playVideo(file.FullName);
}
I started thinking what I am doing is a cross thread violation but why does it always work why am I not receiving a thread violation in Visual Studio when I run the project in debug mode like I always do when I attempt to assign textBox1.text in onData? I have a feeling it has something to do with axWMP being an activex COM object but still seems I should eventually have a cross thread exception on this if it is?
If it is a cross thread violation do I need to do a BeginInvoke/Invoke around axWMPn[0] assignment?
Thanks for any advice...
Hi I am attempting to use websocket-sharp to open a socket to connect to my node.js backend, but I am running into a compiler error listed below. However, all the examples using websocket-sharp seem absolutely identical. I am at a loss at this point, and was hoping someone could point me in the right direction.
COMPILER ERROR Delegate System.Func' does not take2' arguments
private void OpenSocket(string cmd){
using (var websocket = new WebSocket ("ws://127.0.0.1:3000/socket.io/?EIO=2&transport=websocket")) {
websocket.OnMessage += (sender, e) => websocket.Send ("Hi There");
websocket.Connect();
websocket.Send ("TEST");
Console.ReadKey (true);
}
}
===Full Code=== https://gist.github.com/MicahRamirez/986f8168b9fa8c4c1e9e
===WebSocket-Sharp Ex Usage=== https://gist.github.com/MicahRamirez/0c23d6aa1b9bf8e5613aO
I'm trying to set up a specific scenario but, obviously, I'm having problems. My server is a site that primarily hosts a WCF service but I want to add an XSockets host there as well. I have the standard code in the bootstrap code file as per the instructions in the readme.txt. Upon a client connection, I am starting a worker thread which is basically a heartbeat that the client will monitor. The relevant code from the controller is as follows:
public class HeartbeatController : XSocketController
{
public void AddMessage(string message)
{
this.SendToAll(message, "addMessage");
}
}
Within my worker thread I am calling this:
string message = String.Format("pump", Math.Round(cpuCounter.NextValue());
ClientPool connection = ClientPool.GetInstance("ws://mywebsite:4502/HeartbeatController", "*");
connection.Send(message, "addMessage");
Currently I'm testing this with a console client which looks like this:
class Program
{
static XSocketClient socketClient;
static void Main(string[] args)
{
Console.WriteLine("Starting client...");
string url = "ws://mywebsite:4502/HeartbeatController";
socketClient = new XSocketClient(url, "*");
socketClient.OnOpen += socketClient_OnOpen;
socketClient.Open();
while (true)
{
// let it sit and display the "pump" messages
string input = Console.ReadLine();
if (input.Equals("Q", StringComparison.Ordinal))
{
break;
}
}
}
static void socketClient_OnOpen(object sender, EventArgs e)
{
Console.WriteLine("socketClient Opened");
socketClient.Bind("addMessage", OnAddMessage);
}
private static void OnAddMessage(ITextArgs textArgs)
{
Console.WriteLine("AddMessage :: {0}", textArgs.data);
}
}
On the client, if I put a breakpoint in the socketClient_OnOpen method it gets hit so I think it is connecting. But the pump message never makes it to the client.
Two Questions:
Is there anything obvious that I'm missing?
(Unrelated) Since many enterprises really don't like punching holes in their firewalls, is there any way to use port 80 with this setup (so that the client connection would look like "ws://mywebsite/HeartbeatController")?
Thanks for any help!
So to see what your pump actually was sending in to the server I added a custom pipeline.
public class MyPipeline : XSocketPipeline
{
//Incomming textmessage
public override void OnMessage(IXSocketController controller, ITextArgs e)
{
Console.WriteLine("IN " + e.data);
//Let the message continue into the server
base.OnMessage(controller, e);
}
//Outgoing textmessage
public override ITextArgs OnSend(IXSocketProtocol protocol, ITextArgs e)
{
Console.WriteLine("OUT " + e.data);
return base.OnSend(protocol, e);
}
}
Since I then saw that you was sending in a string that actually did not have a property named "message". The actionmethod "AddMessage" expects you to pass in a property message of type string. So you can solve this in two ways, both of them are simple.
Just replace the string parameter in the AddMessage with ITextArgs
public void AddMessage(ITextArgs message)
or...
Pass in a object from your worker thread instead of a string like this
connection.Send(new {message}, "addMessage");
So all you need to do to get it to work is to change this row
connection.Send(message, "addMessage");
with this row
connection.Send(new {message}, "addMessage");
EDIT: Btw, 4.0 is on the way and the client will be very much improved as well as the serverside stuff.
I need to make a simple http client in C# that must be asynchronous and must support a persistent connection to the server. So i'm trying to use the WebClient class, but i'm having some problems, my code is this:
void sendMessage()
{
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(bypassAllCertificateStuff);
string loginRequest = #"{'IDENTIFIER':'patient1','PASSWORD':'asdasd','DEVICE_ID':'knt-01'}";
client = new WebClient();
// add event handlers for completed and progress changed
client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged);
client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
// carry out the operation as normal
client.UploadStringAsync(new Uri("Https://192.168.1.100/PaLogin"), "POST", loginRequest);
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine("downloadProgressChanged");
}
void client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
// Console.WriteLine(e.ProgressPercentage);
if (e.ProgressPercentage != 50)
{
Console.WriteLine("uploadProgressChanged");
}
}
void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Result != null)
{
Console.WriteLine("Done");
}
}
The problem is that i should receive a response from the server, but neither the client_UploadStringCompleted nor client_DownloadProgressChanged callbacks are ever called.
The only thing I see on the console is: client_DownloadProgressChanged
So basically what i'm trying to do is:
1- I send some data to the server without closing the connection
2- I receive the server response but the connection must still be open when i have received it.
What am I missing?
Thank you. :-)
You are missing the whole HTTP protocol here.
HTTP is a stateless request-response protocol. HTTP 1.1 provides optional guidelines for keeping connections open purely for the sake of performance - although as for the request response paradigm, there is no change. [Yet I have seen many cases where client or server have decided not to respect it and closed the connection.] It also provides chunked encoding to facilitate streaming, but that is all it is as far as HTTP is concerned.
So basically in HTTP, client will wait for a reply (and keep connection open) until it receives a response or timeout. There is no way to change/better this behaviour.
NOW, back to you problem.
I think something is going wrong with connecting to the server so you need to use Fiddler to see what is happening. My hunch is it does not connect to server (firewall, server down, etc) since the certificate check is not even called.
Http server push mechanism can do this.
See this:
http://en.wikipedia.org/wiki/Comet_(programming))
c# client:
using (var client = new WebClient())
using (var reader = new StreamReader(client.OpenRead(uri), Encoding.UTF8, true))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
(che รจ quello che vi dicevo questo pomeriggio)