socket.on('sign_in', function(idA, idB) {
var idA = idA; //global vars
var idB = idB; //ignore this var
if (!clients[idA]) {
clients[idA] = socket.id;
}
console.log(idA + ' has connected');
io.to(clients[idA]).emit('sign_in', idA + ' has connected'); });
io.emit('sign_in', "user is signed in");
I am trying to emit the message,"'idA' has connected" to my android client. The problem is that the emitting to a specific client only works once. After it is called once the server stops sending the line "'idA' has connected". I have to reset my server in order to get it to work again, but the problem lingers. The basic io emit function consistently works which leads me to think its a problem with the specific client emit.
I have tried adding the option 'forceNew' to my socket connection but it does not change anything (I am using nkzawa socket-client).
my client code:
IO.Options options = new IO.Options();
options.forceNew = true;
socket = IO.socket(HOST, options);
and then using a new thread:
new Thread(new Runnable() {
#Override
public void run() {
Log.i(TAG, "attempting to connect socket");
socket.connect();
idA = "user1"
idB = "nicknameOfUser1"
socket.emit("sign_in", idA, idB);
}
}).start();
receiving the emit:
socket.on("sign_in", new Emitter.Listener() {
#Override
public void call(Object... args) {
String message = (String) args[0];
System.out.println(message);
}
});
Again, the message "'idA' has connected" will only print out the first time. But the message "user has signed in" is called consistently each time.
Turns out that my emit was written incorrectly.
io.to(clients[idA]).emit('sign_in', idA + ' has connected');
should be
clients[idA].emit('sign_in', idA + ' has connected');
also be sure to assign
clients[idA] = socket;
Related
I'm trying to connect my android app to a nodeJS server using Socket.io
this is the connection code from android:
final String URL = "http://192.168.0.103:3000";
try {
mSocket = IO.socket(URL);
mSocket.connect();
mSocket.emit("message", "Hello");
Toast.makeText(MainActivity.this, "Socket Connected!!",Toast.LENGTH_SHORT).show();
} catch (URISyntaxException e) {
e.printStackTrace();
}
nothing more on android, also I have my internet permission added to manifest and I'm using next library:
implementation 'com.github.nkzawa:socket.io-client:0.6.0'
On the server-side, I'm using also Socket.io library, but for nodeJS and the connection is made like in following lines of code:
const app = express();
app.set("port", process.env.PORT || 3000);
let http = require("http").Server(app);
let io = require("socket.io")(http);
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Content-Type", "application/json");
next();
});
app.get("/", (req: any, res: any) => {
res.send("hello world");
});
io.on("connection", function(socket: any) {
console.log("a user connected");
// whenever we receive a 'message' we log it out
socket.on("message", function(message: any) {
console.log(message);
});
});
const server = http.listen(3000, function() {
console.log("listening on *:3000");
});
When I'm trying to connect from android any line of code is executed with success, even the Toast message, but on server nothing. Also, I made a little script on nodeJS using "socket.io-client" library, for testing where I'm trying to connect to the same server and all the stuff is working fine, the connection is created with success, I receive the message on the terminal from the server, and from the script also I have a success message. the following script looks like this:
var io = require("socket.io-client");
function checkSocketIoConnect(url, timeout) {
return new Promise(function (resolve, reject) {
var errAlready = false;
timeout = timeout || 5000;
var socket = io(url, { reconnection: false, timeout: timeout });
// success
socket.on("connect", function () {
clearTimeout(timer);
resolve();
socket.close();
});
// set our own timeout in case the socket ends some other way than what we are listening for
var timer = setTimeout(function () {
timer = null;
error("local timeout");
}, timeout);
// common error handler
function error(data) {
if (timer) {
clearTimeout(timer);
timer = null;
}
if (!errAlready) {
errAlready = true;
reject(data);
socket.disconnect();
}
}
// errors
socket.on("connect_error", error);
socket.on("connect_timeout", error);
socket.on("error", error);
socket.on("disconnect", error);
});
}
checkSocketIoConnect("http://192.168.0.103:3000").then(function () {
// succeeded here
console.log("working");
}, function (reason) {
// failed here
console.log("why not: ", reason);
});
I am trying to use the following code which is an implementation of web sockets in Netty Nio. I have implment a JavaFx Gui and from the Gui I want to read the messages that are received from the Server or from other clients. The NettyClient code is like the following:
public static ChannelFuture callBack () throws Exception{
String host = "localhost";
int port = 8080;
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new RequestDataEncoder(), new ResponseDataDecoder(),
new ClientHandler(i -> {
synchronized (lock) {
connectedClients = i;
lock.notifyAll();
}
}));
}
});
ChannelFuture f = b.connect(host, port).sync();
//f.channel().closeFuture().sync();
return f;
}
finally {
//workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
ChannelFuture ret;
ClientHandler obj = new ClientHandler(i -> {
synchronized (lock) {
connectedClients = i;
lock.notifyAll();
}
});
ret = callBack();
int connected = connectedClients;
if (connected != 2) {
System.out.println("The number if the connected clients is not two before locking");
synchronized (lock) {
while (true) {
connected = connectedClients;
if (connected == 2)
break;
System.out.println("The number if the connected clients is not two");
lock.wait();
}
}
}
System.out.println("The number if the connected clients is two: " + connected );
ret.channel().read(); // can I use that from other parts of the code in order to read the incoming messages?
}
How can I use the returned channelFuture from the callBack from other parts of my code in order to read the incoming messages? Do I need to call again callBack, or how can I received the updated message of the channel? Could I possible use from my code (inside a button event) something like ret.channel().read() (so as to take the last message)?
By reading that code,the NettyClient is used to create connection(ClientHandler ),once connect done,ClientHandler.channelActive is called by Netty,if you want send data to server,you should put some code here. if this connection get message form server, ClientHandler.channelRead is called by Netty, put your code to handle message.
You also need to read doc to know how netty encoder/decoder works.
How can I use the returned channelFuture from the callBack from other parts of my code in order to read the incoming messages?
share those ClientHandler created by NettyClient(NettyClient.java line 29)
Do I need to call again callBack, or how can I received the updated message of the channel?
if server message come,ClientHandler.channelRead is called.
Could I possible use from my code (inside a button event) something like ret.channel().read() (so as to take the last message)?
yes you could,but not a netty way,to play with netty,you write callbacks(when message come,when message sent ...),wait netty call your code,that is : the driver is netty,not you.
last,do you really need such a heavy library to do network?if not ,try This code,it simple,easy to understanding
I have configured one xbee pro as coordinator (API mode) and other as router (API mode). I trying to send data from coordinator to router using xbee java api, but in the router code i keep getting null, am I doing something wrong.
Below is the code for Sending data (coordinator):
public class MainApp {
private static final String PORT = "/dev/ttyUSB0";
private static final int BAUDRATE = 9600;
public static void main(String[] args)
{
String data = "Helloww";
XBeeDevice mycord = new XBeeDevice(PORT, BAUDRATE);
try {
mycord.open();
System.out.println("Port is opened\n");
System.out.println("remote device connection\n");
//mac of my router
RemoteXBeeDevice router = new RemoteXBeeDevice(mycord,
new XBee64BitAddress("0013A20040DD9BDD"));
System.out.println("Sending data\n");
mycord.sendData(router, data.getBytes());
} catch (XBeeException e) {
e.printStackTrace();
mycord.close();
System.exit(1);
}
}
}
code on router side
public class RecvApp {
private static final String PORT = "/dev/ttyUSB1";
private static final int BAUDRATE = 9600;
public static void main(String[] args)
{
XBeeDevice myrouter = new XBeeDevice(PORT, BAUDRATE);
try {
myrouter.open();
System.out.println("router port opened\n");
//mac of coordinator
RemoteXBeeDevice remotecord = new RemoteXBeeDevice(myrouter, new XBee64BitAddress("0013A20040D96FE5"));
XBeeMessage msg = myrouter.readDataFrom(remotecord);
System.out.print(msg);
} catch (XBeeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myrouter.close();
System.exit(1);
}
}
}
On the router you need to have a loop that checks for messages and prints them out. The API should have a method you can call to check for messages before calling readDataFrom() (or maybe you just ignore the null response). Sleep for a few milliseconds between each check. Right now, there isn't much opportunity for your message to come through before the program quits.
When debugging something like this, start by isolating your problem. Which side is failing, the coordinator or the router? Are you sure the XBee modules have joined to each other and are on the same network?
One test would be to run a simple terminal emulator on the serial port connected to the router, do you see any frames coming through? If you look at a hex dump of the bytes, do you see your "Helloww" message? If not, you need to get the coordinator working first before you debug your router.
Found the issue, I was not converting the message received in the correct format. Added the below lines
String content = HexUtils.prettyHexString(HexUtils.byteArrayToHexString(xbeeMessage.getData()));
System.out.println("Hex data" + "" + content + "\n");
String value = new String(xbeeMessage.getData());
System.out.print("Actual msg" + " " + value + "\n");
Works now :)
I'm newbie to the web-socket programming...
I have the following JavaScript client code:
var connection = new WebSocket('ws://localhost:8080/OmegaThings/registerdevice');
connection.onopen = function () {
console.log("Socket has been opened state = " + connection.readyState);
connection.send('Ping'); // Send the message 'Ping' to the server
connection.send('Websocket client');
};
console.log("Socket has been opened state = " + connection.readyState);
connection.send('finish');
// Log errors
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
// Log messages from the server
connection.onmessage = function (e) {
console.log('Server: ' + e.data);
};
Java endpoint:
#ServerEndpoint("/registerdevice")
public class RegisterDeviceEndPoint
{
private static final Logger LOG = Logger.getLogger(RegisterDeviceEndPoint.class.getName());
#OnOpen
public void connectionOpened()
{
LOG.log(Level.INFO, "******************connection opened**************");
}
#OnMessage
public synchronized void processMessage(Session session, String message)
{
LOG.log(Level.INFO, "received message: {0}", message);
}
#OnClose
public void connectionClosed()
{
LOG.log(Level.INFO, "connection closed");
}
}
on the firefox console I got the following output:
"Socket has been opened state = 1"
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
"Socket has been opened state = 0"
on the GlassFish server log I got "ping" and "Websocket client", but the connection closed after onopen event exit(not sure), thus, the last word "finish" doesn't appear on the log and the error occurs.
I want to know if my code is correct?
What causes the error? javascript code, GlassFish server configuration or the java endpoint code?
Try to change the glassfish 8080 port, eg: 8887, or make sure Your antivirus/other application are not using port 80, I previously had experience where my server websocket was blocked by antivirus which using port 80.
Good morning, I have the following code:
int numero = 22492;
String PhnNoStr = String.valueOf (numero);
String transaction = WriteText(tipoTransacao);
String SmsStr = "ECART" + "" + transaction + idToken;
System.out.println ("Message:" + smsStr);
MessageConnection msgCon = null;
msgCon = (MessageConnection) Connector.open ("sms :/ /" + + phnNoStr ": 500");
TextMessage TxtMsg = (TextMessage) msgCon.newMessage (MessageConnection.TEXT_MESSAGE);
txtMsg.setPayloadText (smsStr);
msgCon.send (TxtMsg);
so I send that message by default it returns me a message. I can send and receive this message, however I need to intercept when I receive this message, does anyone know how I can do this?
Thank you
You can use PushRegistry to have your midlet launched when a SMS is received and midlet is not running.
PushRegistry.registerConnection("sms://:500", "your_package.Your_MIDlet", "*");
To handle incoming SMS, you need to open connection and listen for incoming message, eg:
class SMSHandler implements MessageListener, Runnable {
public void start() {
...
connection = (MessageConnection) Connector.open("sms://:500", Connector.READ);
connection.setMessageListener(this);
}
public void notifyIncomingMessage(MessageConnection messageConnection) {
(new Thread(this)).start();
}
public void run() {
final Message message = connection.receive();
...
}
(The reason for processing the message in another thread is that blocking I/O should not be done in system callback - at least WTK emulator will print warning, and on some phones midlet will just freeze).