.net micro framework and socket.io - http

I have 2 questions:
question (1):
I want to connect my Gadgeteer who works on .net micro framework v4.2 via TCP to a server i wrote on node.js, but I am just stuck on
socket.Connect(new IPEndPoint(IPAddress.Parse(ip_address), port));
it's just loading. I have an ethernet module and I read at https://netmf.codeplex.com/releases/view/81000 under the title bug fixes that "Socket.Connect still blocked after reinsert ethernet cable" have this been fixed or not?
The code is:
Connecttoserver(settings.IPAddress, 8000);
void Connecttoserver(string ip_address, int port)
{
try
{
socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
socket.Connect(new IPEndPoint(IPAddress.Parse(ip_address), port));
Send("HI !");
ReceiveThread = new Thread(Receive);
ReceiveThread.Start();
}
catch (Exception x)
{
}
}
Question (2):
I want to use socket.io who is using websockets instead of TCP/IP but when I try the example from this webside https://github.com/nikkis/SocketIO.NetMF/. I can see in the output that the message has been sent but nothing happens, the server is never connected to my Gadgeteer?
Can somebody help me with a socket.io server who send data to the client directly not to the browser. is that possible with socket.io in node.js?

To your question (2):
Which version of Socket.IO you have for Node.js? I think the library supports version 0.9.x.
Can you tell what your Node.js logs say when you try to connect your Gadgeteer? Does it receive connection event? Bellow an example to set up Node.js socket.io that should work with the library.
var server = APP.listen( config.server.port );
var io = socket.listen( server );
io.sockets.on( 'connection', function( socket ) {
console.log( 'connection' );
socket.on( 'disconnect', function( deviceid ) {
console.log( 'disconnecting ' + socket.id );
} );
socket.on( 'my_own_event', function( param1, param2 ) {
console.log( 'executing my own event' );
} );
}

Related

Titanium TCP/IP socket read buffered data

I am reading a tcp-ip socket response (JSON) from the server. The issue is that sometimes if the data that is received from the server is very large it comes in batches of 2 or 3 with a random break in the JSON. Is there a way to detect how many batches are being sent from the server or is there a mechanism to tackle this at the client end? Below is the titanium code for TCP/IP:
var socket = Ti.Network.Socket.createTCP({
host: '127.0.0.1',
port: 5000,
connected: function (e) {
Ti.API.info('Socket opened!');
Ti.Stream.pump(socket, readCallback, 2048, true);
},
error: function (e) {
Ti.API.info('Error (' + e.errorCode + '): ' + JSON.stringify(e));
},
});
socket.connect();
function writeCallback(e) {
Ti.API.info('Successfully wrote to socket.'+JSON.stringify(e));
}
function readCallback(e) {
Ti.API.info('e ' + JSON.stringify(e));
if (e.bytesProcessed == -1)
{
// Error / EOF on socket. Do any cleanup here.
Ti.API.info('DONE');
}
try {
if(e.buffer) {
var received = e.buffer.toString();
Ti.API.info('Received: ' + received);
} else {
Ti.API.error('Error: read callback called with no buffer!');
socket.close();
}
} catch (ex) {
Ti.API.error('Catch ' + ex);
}
}
TCP/IP is a streaming interface and there is no guarantee from the client side how much data will be received when a read is attempted from the socket.
You would have to implement some sort of protocol between the server and the client.
TCP/IP Protocol is not designed like that, you cannot know how much data you will receive, it's in darkness lol
There are two ways to solve this problem, as I know.
The first One is EOF, you will add something as a prefix at the end of the packet, and it's a unique string like [%~Done~%]
so? you will receive everything and search in it about this string, did you find it? let's go to processing.
but I saw it as wasting of time, memory, and very primitive
the second one is Prefix Packet header, and it's the best for me, an example in .NET can be located here: Thanks to Stephen Cleary

Connecting to socket.io socket with R

I am trying to connect to a socket.io socket in R using the R function socketConnection(). However, although I am able to set up the socket properly, I am not able to read data from it into R.
The javascript code I use to set up the server is:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(8005);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
setInterval(function() {
socket.emit('update', "test")
}, 1000);
});
The code for index.html is:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:8005');
socket.on('update', function (data) {
console.log(data);
});
</script>
I am able to verify that the socket is indeed working by going to localhost:8005 in my web browser and opening up the Developer's Console, where I can see "test" being logged. However, when I try to connect to the socket in R by:
sock <- socketConnection("localhost", 8005, blocking = FALSE, open = "r")
readLines(sock)
Every time I run readLines(sock) I get an empty character vector back. I have also confirmed I can read from other sockets in R by executing the following and indeed getting a response from readLines(sock):
sock <- socketConnection("rstudio.com", 6789, blocking = FALSE, open = "r")
readLines(sock)
Any help would be greatly appreciated. Thanks!
UPDATE (2015-09-01):
Thanks to the excellent help from Aaron Dufour, I was able to adapt this net server demo to stream data into R. The javascript code I used for the server was
var net = require('net');
var server = net.createServer(function(socket) {
setInterval(function() {
socket.write('Test\r\n');
socket.pipe(socket);
}, 1000)
});
server.listen(1337, '127.0.0.1');
And the R code was:
sock <- socketConnection("localhost", 1337, open = "r")
readLines(sock)
close(sock)
I did get the following warning warning: possible EventEmitter memory leak detected. 11 end listeners added. Use emitter.setMaxListeners() to increase limit. sometimes on the server side when I ran readLines(socket)
Also, when I ran close(socket) in R the server crashed and I get the following error: Error: This socket has been ended by the other party
With additional research, I think both the warning and error are preventable.
As I've described here, the socket.io protocol is much more than a WebSocket. Just opening a WebSocket to it won't work.
But socketConnection appears to not even be a WebSocket, but rather a raw socket. You're getting nothing back because the server is talking HTTP and you haven't finished sending an HTTP request.
You probably need a socket.io library for R, or to switch away from socket.io on the server.

Using meteor sockjs connection to send arbitrary messages to the client

I would like to send arbitrary messages to an specific DDP client.
For instance calling "write" from the server:
Meteor.server.sessions[ session_id ].socket.write( { data_for_user: "something" } )
But i'm not sure how i'm supposed to "catch" this messages on the client.
I know the following code doesn't work, but i would like to achieve something among this lines:
DDP.client.onmessage( function( data ) {
// i'm guessing i would have to filter my messages
// since all DDP messages fire here?
if( data.data_for_user ) {
// Do i need to tell DDP to don't parse my custom message?
console.log( "got something for you", data )
}
} );
you can catch DDP messages on client like this.
var original = Meteor.connection._livedata_data;
Meteor.connection._livedata_data = function (msg) {
console.log(msg)
return original.call(this, msg);
}

SignalR self host connection issue

I recently created a proof of concept console application using SignalR (self host). It worked a treat for our use. The client connected fine and I was able to send updates from the server to the client. Lovely!
I've now transferred the code from the Console application to a winforms application for a prettier UI. Now that same client won't connect to the server yet it will still connect to the old Console version.
Winforms code:
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
// Let the app know the server is up
}
Console code:
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
Client connection code:
if (!connected)
{
int i = 0;
// Try 3 times
while (i <= 2)
{
try
{
string server = Properties.Settings.Default.Server + ":" + Properties.Settings.Default.PortNumber.ToString();
connection = new HubConnection(server);
connection.StateChanged += connection_StateChanged;
hub = connection.CreateHubProxy("MyHub");
connection.Start().Wait();
hub.On<string>("addMessage", param => { UpdateAlarmStatus(param); });
return true;
}
catch (Exception)
{
i++;
}
}
return false;
}
else
{
return true;
}
The error the client is reporting is:
Exception:Thrown: "No connection could be made because the target machine actively refused it" (System.Net.Sockets.SocketException)
A System.Net.Sockets.SocketException was thrown: "No connection could be made because the target machine actively refused it"
Time: 25/01/2015 15:09:23
Thread:Worker Thread[8232]
Why would the target machine (localhost) refuse itself which the Console version doesn't? I've been looking at the code over and over and I cannot see where I'm going wrong. Can anyone point me in the right direction please?
Thank you for reading.
Paul.
I suspect this is an issue with the configuration of your machine/infrastructure rather than the code itself, which looks fine at first glance.
Have you checked the console debug output in Visual Studio? I recently encountered an issue with similar symptoms and that was what gave me the initial clue to keep investigating. In my particular case, an exception was written to the console debug output that didn't make it to the client.
SignalR will normally negotiate with the server automatically to determine the best transport method to use. In a .NET client, the available options are LongPollingTransport, ServerSentEventsTransport and WebSocketTransport. So for some reason, your console app can use at least one of those methods, whereas your WinForms client cannot.
You can perhaps enable tracing to give you more information to work with. To do this, enter the below before you create the hub proxy:
hubConnection.TraceLevel = TraceLevels.All;
hubConnection.TraceWriter = Console.Out;
ASP.NET doco on SignalR tracing

SignalR connect error

I use SignalR 2.0.0 Win2012 iis8 with two environment with two different ips.
one environment service is up and second is down(purposely)
use websocket protocol.
i have the following scenario:
When i connect to first environment and want to connect to the second.
i disconnected from first environment and try connect to second environment i get error(its correct behavior)
i try to reconnect back to the first environment but I get still the same error.
the error is "Error during negotiation request."
after refresh the browser i can connect success again to first environment.
What am i doing wrong?
this is part of my code:
function connect(host)
{
var hubConnection = $.hubConnection.('');
hubConnection.url = host;
hubConnection.start()
.done(open)
.fail(error);
}
function open()
{
console.log('login success')
}
function disconnect()
{
var self = this,
hubConnection = $.hubConnection("");
console.log('disconnect ')
hubConnection.stop(true, true);
}
function error(error)
{
var self = this,
hubConnection = $.hubConnection("");
console.log('connection error ')
if(error && hubConnection.state !== $.connection.connectionState.connected)
{
.....
.....
//logic detemninate wich environment ip was previous
connect(environment ip)
}
}
//occured when button disconnect clicked
function disconnectFromFirstEnvironmentAndConnectToSecond()
{
disconect();
connect(second environment ip);
}
.....
.....
connect(first environment ip);
You're not retaining your first connection reference.
Aka you create a HubConnection and then never capture it in a scope that can be used later; therefore when you disconnect later the connection.stop does nothing because it's not calling stop on the HubConnection that was originally started.
This could ultimately lead to you having too many concurrently open requests which will then not allow you to negotiate with a server hence your error.
I'd recommend fixing how you stop/start connections. Next if the issue still occurs I'd inspect the network traffic to ensure that valid requests are being made.

Resources