Compiler Error on Anonymous Callback Method for WebSocket-Sharp Event - c#

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

Related

Is there a simple way of catching disconnect events to a NATS connection in C#

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.

Send message directly to user

I wish to send messages to a client directly via their IP address. I am currently only able to send messages when ChannelRead0 is called in the handler and grabbing the context from there:
protected override void ChannelRead0(IChannelHandlerContext ctx, DatagramPacket packet) {
ctx.WriteAsync(new DatagramPacket(buffer, packet.Sender));
}
My bootstrapper:
var bootstrap = new Bootstrap();
bootstrap
.Group(group)
.Channel<SocketDatagramChannel>()
.Option(ChannelOption.SoBroadcast, true)
.Handler(new LoggingHandler("SRV-LSTN"))
.Handler(new ActionChannelInitializer<IChannel>(channel => {
channel.Pipeline.AddLast("UDPServer", new protocols.UDP());
}));
IChannel boundChannel = await bootstrap.BindAsync(8888);
I want to be able to send messages from outside this function as well. Is there any way in which I can send a client a message from outside this function / class? I have tried writing to boundChannel however it appears that it doesn't wave a .write or .writeAsync function.
I am using the DotNetty library (https://github.com/Azure/DotNetty) which was ported from Java.
An IChannel has an WriteAndFlushAsync method that you can use to write a message, this is similair to the writeAndFlush method in the Java version of Netty.

socketio4net error initializing handshake

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;

debugging sockets and DLL's

First question now answered if you want to skip to the bottom..
I'm developing comms between PDA's on .net 2.0 and our servers. Can't use WCF or I would have.
The comms model is like this:
And fortunately i've found working code form http://aviadezra.blogspot.com/2008/07/code-sample-net-sockets-multiple.html - that's where the image above comes from too.
The example app has messages from each client being broadcast to all other clients. I would like to be able to send a message from one client to another specific client. To do this i've modified the client app to have a from-ID and To-ID which is sent as part of the message.
Note: At this stage i'm doing proof of concept - i'll work on things like message headers (lengths, versions etc later).
From the project each client connection is handled by:
private void OnClientConnection(IAsyncResult asyn)
{
if (m_Closed)
{
return;
}
try
{
Socket clientSocket = m_socket.EndAccept(asyn);
RaiseClientConnected(clientSocket);
ConnectedClient connectedClient = new ConnectedClient(clientSocket);
connectedClient.MessageRecived += OnMessageRecived;
connectedClient.Disconnected += OnClientDisconnection;
connectedClient.StartListen();
long key = clientSocket.Handle.ToInt64();
if (m_clients.ContainsKey(key))
{
Debug.Fail(string.Format(
"Client with handle key '{0}' already exist!", key));
}
m_clients[key] = connectedClient;
// create the call back for any client connections...
m_socket.BeginAccept(new AsyncCallback(OnClientConnection), null);
}
catch (ObjectDisposedException odex)
{
Debug.Fail(odex.ToString(),
"OnClientConnection: Socket has been closed");
}
catch (Exception sex)
{
Debug.Fail(sex.ToString(),
"OnClientConnection: Socket failed");
}
}
Class connectedClient holds the socket for that client.
When I send a message from client I do a lookup to see if that's in my list of sockets:
if (ListIDSocket.ContainsKey(ToID))
{
PublishMessage(listLog, "ToID Found");
SendAll = false;
}
ListIDSocket is:
private Dictionary<string, Socket> ListIDSocket = new Dictionary<string, Socket>();
Then..
if (SendAll)
m_ServerTerminal.DistributeMessage(buffer);
else
m_ServerTerminal.SendToSocket(ToID, socket, buffer);
So if message is to anyone, call DistributeMessage; if to single user, call SendToSocket.
The code in m_ServerTerminal is:
public void DistributeMessage(byte[] buffer)
{
try
{
foreach (ConnectedClient connectedClient in m_clients.Values)
{
connectedClient.Send(buffer);
}
}
catch (SocketException se)
{
Debug.Fail(se.ToString(), string.Format(
"Buffer could not be sent"));
}
}
public void SendToSocket(string ToID, Socket DestSocket, byte[] buffer)
{
DistributeMessage(buffer); // This line works
ConnectedClient ToClient;
long keyval = DestSocket.Handle.ToInt64();
if (m_clients.ContainsKey(keyval))
{
ToClient = (ConnectedClient)m_clients[keyval];
try
{
ToClient.Send(buffer); // Nothing is received
}
catch (SocketException se)
{
Debug.Fail(se.ToString(), se.Message);
}
// DistributeMessage(buffer); // This code here doesn't work
}
}
DistributeMessage works fine. For debugging purposes i've included a call to DistributeMessage in my SendToSocket and this works if it's at the top.
If I move it down after I try writing to to the socket, it doesn't.
I don't get an exception on either way.
As it stands now, client gets one message when it should get two - one from DistributeMessage and one from SendToSocket.
The code for connectedclient.Send is:
public void Send(byte[] buffer)
{
if (m_clientSocket == null)
{
throw new Exception("Can't send data. ConnectedClient is Closed!");
}
m_clientSocket.Send(buffer);
}
Questions:
I can't see anything that i'm doing substantially different with my new code to existing but the socket isn't being written to. Can anyone spot anything obvious ? Is this something to do with sockets, handles and references to them ?
EDIT: Bug found, whilst I was looking up to see if the socket existed, I was passing in the socket of the sender not receiver. I'll fix this.
Debugging DLL's I'd still like to know about though..
Secondly, the project is setup with the socket handling in it's own DLL called Communication.Sockets.Core. I've never built DLL's before and i'm having trouble debugging. Can't use normal debug points in code - I resorted to creating a form to display instead.
Any tips on how to debug DLL's ?
I'm still fairly new to C#; just on 1 year.
TIA,
Andrew

C# async persistent WebClient example

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)

Categories

Resources