SignalR doesn't echo - xamarin.ios

I'm trying out SignalR.
I started out by making a hub with one method Echo. The hub calls a method "echoed" on the client on connection as well as from the Echo method. The client sees the first call to "echoed" that happens in OnConnected but doesn't see the one from Echo that it calls itself. I suspect the reason is that on the server the hub is instantiated in two different appdomains for both calls.
--- UPDATE: ---
By setting "Maximum Worker Processes" to 1 in IIS Manager (under Application Pools/My app pool/Advanced Settings) the application is forced in a single AppDomain and the callback echo works. Is there a way to make it work with multiple worker processes?
public override System.Threading.Tasks.Task OnConnected()
{
Log.WriteLine("SIGNALR CONNECTED: " + Context.ConnectionId);
Clients.All.Echoed("now connected: "+Context.ConnectionId);
return base.OnConnected();
}
public void Echo(string data)
{
Log.WriteLine("SIGNALR ECHO: " + data);
Clients.All.Echoed(data);
}
The client is .NET (Xamarin for that matter) and it tries to send itself an echo message:
try{
System.Net.ServicePointManager.DefaultConnectionLimit = 10;
HubConnection hubConnect = new HubConnection ("http://localhost:1234/signalr");
hubConnect.Closed+=()=> Console.WriteLine("CLOSED");
hubConnect.Error+=(e)=>Console.WriteLine("ERROR: "+e);
hubConnect.Received+=(s)=>Console.WriteLine("RECEIVED: "+s);
hubConnect.Reconnected+=()=>Console.WriteLine("Reconnected");
IHubProxy ordersHubProxy = hubConnect.CreateHubProxy ("OrdersHub");
ordersHubProxy.On<string> ("Echoed", (echo) =>{
Console.WriteLine ("ECHOED: " + echo );
});
hubConnect.Start().Wait();
Console.WriteLine("CONNECTED: "+hubConnect.Transport.Name);
ordersHubProxy.Invoke("echo", "callback");
} catch (Exception x){
Console.WriteLine ("Unable to connect to SignalR: " + x);
};
On the client side I see an "echoed" event with "now connected: xyzguid" message but I don't see the "callback" message. On the server side there are logged events for both the connection and the echo but the echo doesn't reach the client that asked for it:
Server log:
LOG AppDomain: /LM/W3SVC/2/ROOT/MyApp-11-130157367321605301 Thread: 35
SIGNALR CONNECTED: 8ab4ef99-a41a-4e33-9aba-086a80e2e4a2
LOG AppDomain: /LM/W3SVC/2/ROOT/MyApp-11-130157367360449370 Thread: 1
SIGNALR ECHO: callback
Client log:
CONNECTED: serverSentEvents
ECHOED: now connected: 5cde92f8-9719-4963-b64f-a8bbe39a72ac
RECEIVED: {
"H": "MyHub",
"M": "Echoed",
"A": [
"now connected: 5cde92f8-9719-4963-b64f-a8bbe39a72ac"
]
I expected to see this as well but it doesn't show up:
ECHOED: callback
RECEIVED: ...

Related

Websocket Message Receiving Failed Detection

Here is ws library..
https://github.com/websockets/ws/blob/master/lib/WebSocket.js
Now How can I use send method such as i can detect the message sending failed? I have tried callback and try catch.. may be i am missing something..
Now I am doing this.. it can send the message..
BulletinSenderHelper.prototype.sendMessage = function(bulletin, device) {
var message = JSON.stringify({
action: 'bulletin:add',
data: bulletin.data
});
if (device.is_active) {
logger.debug('Sending message to %s', device.id);
device.conn.send(message); // device.conn == ws . though i am checking it is active or not, sometimes it fails to send the message. i have to detect it.
} else {
logger.debug('Client %s is inactive, queuing bulletin', device.id);
this.queueBulletin(device, bulletin);
}
};

My server gets stuck by Thread.sleep?

I have this code executed as a thread for each client to detect the disconnection of an user in my server:
private void detectDisconnect (Client user)
{
try
{
boolean listening = true;
while (listening)
{
System.out.println("<" + user.getUserName() + "> Sleeping...");
user.setDisconnected(true);
send(user, "heartBeat#");
Thread.sleep(Main.LATENCY);
System.out.println("<" + user.getUserName() + "> I wake up!");
if (user.isDisconnected()) { listening= false; exitClient(user);
}
}
catch (InterruptedException e) { e.printStackTrace(); }
}
The server before of sleeping put user.setDisconnected(true); and if the client send a response before of waking up I change to user.setDisconnected(false); in other method(), so this thread won't exit the Client unless in the latency's period doesn't get any message... This works fine, but sometimes randomly I could check that after the message of "Sleeping..." does not appear the message "I wake up!" (!!!), and the worst thing is that ALL MY PROGRAM GETS FROZEN, so the server doesn't listen or send messages to any client anymore :( even being these in separated Threads executing!....
I don't know why this happen, but I think that all the problems are caused by some eventually fatal error in Thread.sleep(). Could be possible? But I don't receiving any error message in the catch(Exception e){}, so I'm going crazy xD
Help please!!

Startup program has intermittant problems connecting to local database

I'm writing an application that runs from the start-up folder, and tries to connect to a local SQLServer2008-r2 database as part of the startup process of the application. The database i'm connecting to is set to use windows authentication, and my connection string in the application is your standard old connection string:
Data Source=localhost\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True
The code to actually establish the connection looks like this:
String connectionstring = "Data Source=localhost\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True";
SqlConnection cn = new SqlConnection(connectionstring);
bool databaseUp = false;
void Start()
{
CheckSQLService();
for (int i = 0; i < 600; i++)
{
if (ConnectToDB())
{
Console.WriteLine("Database is up and running.");
databaseUp = true;
}
else
{
Console.WriteLine("Database Connection Failed");
CheckSQLService();
Console.WriteLine("Trying again");
Thread.Sleep(1000);
}
}
if(!databaseUp)
{
Console.WriteLine("Database Not Connected: exited loop.");
}
}
bool ConnectToDB()
{
try
{
cn.Open();
return true;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
}
void CheckSQLService()
{
System.ServiceProcess.ServiceController SC = new System.ServiceProcess.ServiceController("MSSQL$SQLEXPRESS");
Console.WriteLine(" = = = Checking SQL Service Status: = = = "
+ "\n ServiceName : " + SC.ServiceName
+ "\n State : " + SC.Status
+ "\n Stoppable : " + SC.CanStop
+ "\n Pausable : " + SC.CanPauseAndContinue
+ "\n Can Shutdown: " + SC.CanShutdown);
}
Basically I loop until I get a connection, and if it fails, I sleep and try again.
Most of the time (about 60%) I am able to successfully establish a connection with no problem on first try. Sometimes, it takes several attempts for this to be successful, and the application waits for some time. I will also note that the read-out of CheckSQLService() verifies every time I call it that the SQL service is running - Only sometimes it rejects my windows credentials apparently.
Anybody have ideas why this might be happening intermittently? Again this is part of an application that runs when windows first starts up, so there could may understandably be many factors at play (e.g. other processes or services not fully loaded, or starting at same time etc).
Just because the SQL Server service is running does not mean it is ready to accept connections.
Since you are always able to connect eventually, and your program runs as the computer is booting, I strongly suspect that you sometimes run before SQL Server is fully initialized and ready for connections.
Many things happen during a typical boot sequence. It is not surprising that your program is sometimes running before SQL Server is ready, and vice-versa.

Log4net remoteAppender output

I am using the remoteAppender inside of the config file and sending the logs remotely to another computer. While sending the information using tcp worked, I found that the remoteAppender was also sending a large chunk of random symbols and characters rather then the log string I want. I suspect that what is being sent by the remoteAppender is not a log string, but rather the logger itself. The method I used to read in the incoming broadcast is simple and taken from the msdm website. Does anyone know of a way to convert the networkstream received back into a string and avoiding all the strange outputs?
public void StartListener()
{
try
{
// Set the TcpListener on port 13000.
Int32 port = 32100;
// TcpListener server = new TcpListener(port);
server = new TcpListener(IPAddress.Any, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.UTF8.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
catch (Exception e)
{
Console.WriteLine("Connection was terminated");
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
here is the output I got when I was sent a log via the remoteAppender:
Waiting for a connection... Connected!
Received: .NET☺ /♥ ♦ ☺☺$ tcp://149.63.90.84:32100/LoggingSink♠ ☺☺↑ appl
ication/octet-stream
Sent: .NET☺ /♥ ♦ ☺☺$ TCP://149.63.90.84:32100/LOGGINGSINK♠ ☺☺↑ APPLICAT
ION/OCTET-STREAM
Received: ☺ ????☺ §¶ ↕ LogEvents↕?☺log4net.Appender.RemotingApp
ender+IRemoteLoggingSink, log4net, Version=1.2.11.0, Culture=neutral, PublicKeyT
oken=669e0ddf0bb1aa2a►☺ ☺ ☻ ♀♥ Klog4net, Version=1.2.11.0, Culture=neu
tral, PublicKeyToken=669e0ddf0bb1
Sent: ☺ ????☺ §¶ ↕ LOGEVENTS↕?☺LOG4NET.APPENDER.REMOTINGAPPENDER+IR
EMOTELOGGINGSINK, LOG4NET, VERSION=1.2.11.0, CULTURE=NEUTRAL, PUBLICKEYTOKEN=669
E0DDF0BB1AA2A►☺ ☺ ☻ ♀♥ KLOG4NET, VERSION=1.2.11.0, CULTURE=NEUTRAL, PU
BLICKEYTOKEN=669E0DDF0BB1
Received: aa2a☻ ☺ ☺ ♦↓log4net.Core.LoggingEvent♥ ♦ ♣♦ ↓log4ne
t.Core.LoggingEvent♂
LoggerName♣LevelMessage
ThreadName TimeStamp♀LocationInfUserName☼ExceptionString
!log4net.Util.Propertity☺♦☺☺ ☻☻☺♦☺☻↕log4net.Core.Level♥
Sent: AA2A☻ ☺ ☺ ♦↓LOG4NET.CORE.LOGGINGEVENT♥ ♦ ♣♦ ↓LOG4NET.CORE.L
OGGINGEVENT♂
LOGGERNAME♣LEVELMESSAGE
THREADNAME TIMESTAMP♀LOCATIONINFUSERNAME☼EXCEPTIONSTRING
!LOG4NET.UTIL.PROPERTITY☺♦☺☺ ☻☻☺♦☺☻↕LOG4NET.CORE.LEVEL♥
Received: iesDictionary♥ ♥ ♠♣ ►Project2.Program ♠ ♠ ♥Hi0 ♦6384?:??
Uf?
♠
♠♂ ‼Project2.vshost.exe
♣♠ ↕log4net.Core.Level♥ ♀m_levelValue♂m_levelName↕m_levelDisplayName ♥ p◄☺
♠♀ ♣ERROR ♀ ♣
!log4net.Util.PropertiesDictionary☺
Sent: IESDICTIONARY♥ ♥ ♠♣ ►PROJECT2.PROGRAM ♠ ♠ ♥HI0 ♦6384?:??
UF?
♠
♠♂ ‼PROJECT2.VSHOST.EXE
♣♠ ↕LOG4NET.CORE.LEVEL♥ ♀M_LEVELVALUE♂M_LEVELNAME↕M_LEVELDISPLAYNAME ♥ P◄☺
♠♀ ♣ERROR ♀ ♣
!LOG4NET.UTIL.PROPERTIESDICTIONARY☺
♂KOLLIK-D1SD♂net_x003A_HostName☺♥ ♠
♂KOLLIK-D1SD♂X003A_HOSTNAME☺♥ ♠
The RemotingAppender uses .NET remoting to proxy log events to an endpoint that implement the log4net.Appender.RemotingAppender+IRemoteLoggingSink interface. It looks like you're trying to simply read the rendered log message via TCP, which is "working" except that, as you point out, your data stream does not contain rendered log strings but remoted binary log events.
Try the TelnetAppender or UDPAppender instead; these appenders render the log message before sending it over the network, so you'll get the string you expect.
See http://logging.apache.org/log4net/release/sdk/log4net.Appender.TelnetAppender.html
and http://maddemcode.com/net/secrets-of-log4net-telnetappender/

NodeJS socket.io-client doesn't fire 'disconnect' or 'close' events when the server is killed

I've written up a minimal example of this. The code is posted here: https://gist.github.com/1524725
I start my server, start my client, verify that the connection between the two is successful, and finally kill the server with CTRL+C. When the server dies, the client immediately runs to completion and closes without printing the message in either on_client_close or on_client_disconnect. There is no perceptible delay.
From the reading I've done, because the client process is terminating normally there isn't any chance that the STDOUT buffer isn't being flushed.
It may also be worth noting that when I kill the client instead of the server, the server responds as expected, firing the on_ws_disconnect function and removing the client connection from its list of active clients.
32-bit Ubuntu 11.10
Socket.io v0.8.7
Socket.io-client v0.8.7
NodeJS v0.6.0
Thanks!
--- EDIT ---
Please note that both the client and the server are Node.js processes rather than the conventional web browser client and node.js server.
NEW ANSWER
Definitely a bug in io-client. :(
I was able to fix this by modifying socket.io-client/libs/socket.js. Around line 433, I simply moved the this.publish('disconnect', reason); above if (wasConnected) {.
Socket.prototype.onDisconnect = function (reason) {
var wasConnected = this.connected;
this.publish('disconnect', reason);
this.connected = false;
this.connecting = false;
this.open = false;
if (wasConnected) {
this.transport.close();
this.transport.clearTimeouts();
After pressing ctrl+c, the disconnect message fires in roughly ten seconds.
OLD DISCUSSION
To notify client of shutdown events, you would add something like this to demo_server.js:
var logger = io.log;
process.on('uncaughtException', function (err) {
if( io && io.socket ) {
io.socket.broadcast.send({type: 'error', msg: err.toString(), stack: err.stack});
}
logger.error(err);
logger.error(err.stack);
//todo should we have some default resetting (restart server?)
app.close();
process.exit(-1);
});
process.on('SIGHUP', function () {
logger.error('Got SIGHUP signal.');
if( io && io.socket ) {
io.socket.broadcast.send({type: 'error', msg: 'server disconnected with SIGHUP'});
}
//todo what happens on a sighup??
//todo if you're using upstart, just call restart node demo_server.js
});
process.on('SIGTERM', function() {
logger.error('Shutting down.');
if( io && io.socket ) {
io.socket.broadcast.send({type: 'error', msg: 'server disconnected with SIGTERM'});
}
app.close();
process.exit(-1);
});
Of course, what you send in the broadcast.send(...) (or even which command you use there) depends on your preference and client structure.
For the client side, you can tell if the server connection is lost using on('disconnect', ...), which you have in your example:
client.on('disconnect', function(data) {
alert('disconnected from server; reconnecting...');
// and so on...
});

Resources