How to check if any application is running on a Datagram Port? - datagram

I have a list of radius servers running on each Datagram Socket and have a list of these started radius servers available with me.
I have a requirement where i need to check if a particular server has been stopped and if stopped i need to restart it.
Below is the code I'm writing but not sure if this is the right way to do it.
Please advice.
....
int port = radiusServer.getAggregation()
.getAuthenticationPort();
try {
// It will throw IO exception if no application is
// running
// on that
// port.
new DatagramSocket(port);
LOGGER.info(
"There is a server running on the Port number {}.",
port);
} catch (IOException e) {
LOGGER.error(
"Server is not running on port number {}.",
port);
startServer(radiusServer);
}
....

The below solution works fine.
try {
// It wont throw IO exception if no application is
// running
// on that
// port.
DatagramSocket ds = new DatagramSocket(port);
ds.close();
LOGGER.warn(
"Server is not running on port number {}. Starting Server",
port);
startServer(radiusServer);
} catch (IOException e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"There is a server already running on the Port number {}.",
port);
}
}

Related

Node stream pipeline stops prematurely

Think of this piece of code as a relay between a NAT-ted service (input) and an external service (output) that wants to communicate with the input.
This relay is on a public server and opens two ports in order to relay:
port 4040 where input connects and forwards the TCP traffic from target service
port 4041 where some external client connects to the relay
The relay should pipe what it receives from input on port 4040 to the external client on port 4041.
I can see both services connecting to the relay but the data flow just stops after, what I suspect the output socket closing. In the following example I used a stream.pipeline but I also tried with simple .pipe directly on the sockets with same results
import net from "net"
import stream from "stream";
export default () => {
const inputServer = net.createServer();
const outputServer = net.createServer();
inputServer.listen(4040, "0.0.0.0", () => {
console.log('TCP Server is running on port ' + 4040 + '.');
});
outputServer.listen(4041, "0.0.0.0", () => {
console.log('TCP Server is running on port ' + 4041 + '.');
});
let inSocket = null;
inputServer.on('connection', (sock) => {
inSocket = sock;
});
outputServer.on('connection', (sock) => {
if (inSocket) {
stream.pipeline(inSocket, sock, (err) => {
if (err) {
console.error('Pipeline failed.', err);
} else {
console.log('Pipeline succeeded.');
}
})
stream.pipeline(sock, inSocket, (err) => {
if (err) {
console.error('Pipeline failed.', err);
} else {
console.log('Pipeline succeeded.');
}
})
}
});
}
My goal is to keep an open socket to the input service and relay with any output will connect.
data flow just stops after, what I suspect the output socket closing
pipeline or .pipe() will automatically close the output stream when the input stream ends so it won't keep your input stream open for successive input stream connections.
Using .pipe(), you can override that behavior by passing an option:
inSocket.pipe(sock, {end: false});
and
sock.pipe(inSocket, {end: false});
You will then need some separate error handling for each stream as .pipe() doesn't do as complete error handling as pipeline() does.
In this way, you let each stream close itself when the client chooses rather than having the server close it when a given streaming operation is complete.
I don't see a similar option for pipeline().
I'm also curious how you plan to use this. Do you intend for there to be one long connected inSocket and many separate connections to the outputServer? Do you intend or need more than one outputServer connection at once? Or just one at at time. Since you're not auto destroying, I wonder if you need to do some manual cleanup (unpiping, for example) when any socket disconnects? .pipe() is also famous for not unwinding all its event listeners which can sometimes lead to GC issues if you don't manually clean up things properly.

Alternative suggestions for this Ping function?

In my game app, I call this:
Runtime.getRuntime().exec("/system/bin/ping -c 1 -w 1 $serverip")
It gives an accurate reading of the ping to my server but in some exceptional cases, the ping doesn't go through in certain circumstances (for example, when the player is using Mobile Data, the command returns nothing in 25% of the cases for no apparent reason).
I am aware there must be other ping commands/functions/methods/protocols to get a ping reading (I am not sure what game companies use in order to get constant ping readings inside their games), any suggestions ? Thanks in advance.
You could also use the Socket class provided in the java.net package.
Using the provided method connect(SocketAddress endpoint) you can connect your socket to the server.
For example, you can use something like this
public static boolean ping(String address, int port) {
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress(address, port));
} catch (IOException e) {
return false;
} finally {
try {
socket.close();
} catch (IOException ignored) { }
}
return true;
}
You can invoke like this ping("www.google.com", 443)
Finally, you could use the java.net.URL class to wrap your String url.
For instance,
URL url = new URL("https://www.google.com:443/");
ping(url.getHost(), url.getPort());

How to prevent repeated responses from Node.js server

We're running into a problem where we're getting multiple responses sent from our Node server to a web client which are connected by a socket server (socket.io). By listening with Docklight, I can see that we're really only getting a single response from the serial device, but for some reason the Node server is sending multiples, and they accumulate, so the first time you send a serial command (and it doesn't matter what commands) might only get a couple, next time a couple more, next time a couple more and so on. So if you run several serial commands, you'll get back lots of multiple responses.
Our environment is Windows 7 64 bit, Node V 4.5.0, serialport V 4.0.1. However, this needs to run on Windows, Mac & Linux when we're done. The dev team (me & one other guy) are both fairly new to Node, but otherwise capable developers.
I think what's happening is I'm not using the .flush() & .drain() functions properly and the serialport buffer still contains serial data. Our proprietary devices return either S>, or <Executed/> prompts when a command has completed, so I store the serial response in a buffer until I see one or the other, then process the data (in this example just providing a boolean response whether the device is responding with one or the other or not). For example, if I send a <CR><LF> to one of our devices, it should respond with S> (or <Executed/> depending).
The client calls into the server with this:
socket.on('getDeviceConnected', readDeviceResponse);
function readDeviceResponse(isDeviceResponding) {
console.log('getDeviceConnected');
console.log(isDeviceResponding);
}
function getDeviceConnected() {
console.log("Sending carriage return / line feed.");
socket.emit('getDeviceConnected', '\r\n');
}
And on the server, here's what I'm trying:
socket.on('getDeviceConnected', function (connectionData) {
//write over serial buffer before the write occurs to prevent command accumulation in the buffer.
serialBuffer = '';
sbeSerialPort.write(connectionData, function (err, results) {
//since there's no way to tell if the serial device hasn't responded, set a time out to return a false after allowing one second to elapse
setTimeout(function () {
console.log('Inside getDeviceConnected setTimeout');
console.log('Is serial device responding:', isSerialDeviceResponding);
if (!isSerialDeviceResponding) {
console.log('Serial device timed out.');
socket.emit('getDeviceConnected', false);
}
}, 1000);
if (err) {
console.log('Serial port error level:', err);
}
if (results) {
if (results === 2) {
console.log('Serial port is responding');
}
}
});
sbeSerialPort.on('data', function (serialData) {
isSerialDeviceResponding = true;
console.log('Does S> prompt exist?', serialData.lastIndexOf('S>'));
while(!serialData.lastIndexOf('S>') > -1 || !serialData.lastIndexOf('<Executed/>') > -1){
serialBuffer += serialData;
break;
}
if (isSerialDeviceResponding) {
socket.emit('getDeviceConnected', true);
isSerialDeviceResponding = true;
}
sbeSerialPort.flush(function (err, results) {
if (err) {
console.log(err);
return;
}
if(results){
console.log('Serial port flush return code:', results);
}
});
});
I'm not very sure about the .flush() implementation here, and I've omitted the .drain() part because neither of them seems to do much of anything (assuming they were correctly implemented).
How do I insure that there is no data left in the serialport buffer when the .write() command is complete? Or do you see other problems with how I'm handling the serial data?
Edit, Source code up on pastebin.com:
Server.js
Client.js
HTML

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!!

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