I am trying to connect my android app to NodeJS server.
ANDROID PART
First I include the Socket.io library to my dependency
implementation('io.socket:socket.io-client:2.0.0') {
exclude group: 'org.json', module: 'json'
}
My JAVA code
//all variables used are initialized, defined and working perfectly
try {
socket = IO.socket(socketUrl);
socket.on(Socket.EVENT_CONNECT, args -> runOnUiThread(() -> socket.emit("connected", true)));
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
SERVER SIDE
var express = require('express'),
app = express(),
socket = require('socket.io'),
router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
var server = app.listen(4000, function(){
console.log('listening for requests on port 4000,');
});
let io = socket(server);
io.on('connection', function(socket){
console.log(`${socket.id} is connected`);
});
module.exports = router;
Now the problem is after starting the Server, and I try to connect my android app to it, I keep getting an error from Socket.io connection, like the image below
I have searched SO for solution and I get multiple answers relating to this, but I still keep getting the same error
My Socket.io version is 8.5.5
you can not use socket directly via express, here is the documentation.
try this code instead.
var express = require('express'),
app = express()
const httpServer = require("http").createServer(app);
const io = require("socket.io")(httpServer);
router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
io.on('connection', function(socket){
console.log(`${socket.id} is connected`);
});
httpServer.listen(4000, function(){
console.log('listening for requests on port 4000,');
});
module.exports = router;
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);
});
What I have:
A simple node server listening on port 8100 for POST requests:
var express = require('express');
var bodyParser = require('body-parser');
var port = 8100;
var app = express();
app.use(bodyParser.json());
app.post('/v1/auth/jwt/login', (req, res) => {
console.log('Here is the body:');
console.log(req.body);
res.json({ message: 'received' });
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
I can confirm that this logs and return a response correctly. (via PostMan/Insomnia/etc)
What I'm trying to do is hit this with a Vert.x webclient:
public void getServiceJwt() {
String loginJwt = getLoginJwt();
System.out.println("Initiating request");
JsonObject payload = new JsonObject()
.put("role", "some-service")
.put("jwt", loginJwt);
client
.post("/v1/auth/jwt/login")
.sendJsonObject(payload, ar -> {
if (ar.succeeded()) {
System.out.println("things went well");
} else {
System.out.println(ar);
System.out.println("something went horribly wrong");
}
});
}
The request happens, as I can see the payload data logged. What seems to not happen is the ar callback. I don't get a log in either case. It's almost as if the request is not returning... but I have no idea how to check. There is no stack trace, no errors. Just, nothing. This example is pretty much right out of the docs.
I'm at a loss on how to troubleshoot this further.
I'm trying to use thrift to relalize communication between nodejs client and Java server
Thrift offer different kinds of java server which have been implemented
· TSimpleServer
· TNonblockingServer
· THsHaServer
· TThreadedSelectorServer
· TThreadPoolServer
I have successfully used nodejs client to call the function in TTSimpleServer and TThreadPoolServer which both use TServerSocket to initialize
TServerSocket serverTransport = new TServerSocket(9090);
CalculatorService.Processor<CalculatorImpl> processor = new CalculatorService.Processor<CalculatorImpl>(
new CalculatorImpl());
TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverTransport).processor(processor);
args.maxWorkerThreads(100);
TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(
serverTransport).processor(processor));
System.out.println("Starting server on port 9090 ...");
server.serve();
but when I try to use TNonblockingServer,TThreadedSelectorServer and THaHsServer , I came acrross following error in nodejs client
{ [Error: read ECONNRESET] code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
I realized that this may be caused by TNonblockingSocket, is there any method to use nodejs communicate with TNonblockingSocket
try
{
TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(
9090);
CalculatorService.Processor<CalculatorImpl> processor = new CalculatorService.Processor<CalculatorImpl>(
new CalculatorImpl());
TServer server = new TThreadedSelectorServer(new TThreadedSelectorServer.Args(
serverTransport).processor(processor));
System.out.println("Starting server on port 9090 ...");
server.serve();
} catch (TTransportException e)
{
e.printStackTrace();
}
my nodejs client code is as follow
var thrift = require('thrift');
var ThriftTransports = require('thrift/transport');
var ThriftProtocols = require('thrift/protocol');
var Calculator = require('./gen-nodejs/CalculatorService.js');
var ttypes = require('./gen-nodejs/tutorial_types');
transport = ThriftTransports.TFramedTransport();
protocol = ThriftProtocols.TBinaryProtocol();
var connection = thrift.createConnection("localhost", 9090, {
transport : transport,
protocol : protocol
});
connection.on('error', function(err) {
console.log(err)
});
// Create a Calculator client with the connection
var client = thrift.createClient(Calculator, connection);
client.send_print(1,1, function(err, response) {
console.log("send_print result:" + response);
});
Well , I just found the answer
This problem is truly caused by TTFramedTransport
i found even when I use this in my code
transport = ThriftTransports.TFramedTransport();
the transport seems not successfully been assigned TFramedTransport
I just try this way
transport = require('./node_modules/thrift/framed_transport.js')
it succeeded
I am not familiar with node.js , maybe I figure out why this happen later
I'm trying to create a simple Websocket connection in my project.
Java code:
#ServerEndpoint("/echo")
public class EchoEndpoint {
#OnMessage
public void onMessage(Session session,String message){
try{
System.out.println(message);
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
html and javascript code:
<button type="button" onclick="WebSocketTest()">Send</button>
<script type="text/javascript">
function WebSocketTest()
{
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:8080/echo");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
}
</script>
after pressing the button I got the errorWebSocket connection to 'ws://localhost:8080/echo' failed: Error during WebSocket handshake: Unexpected response code: 404
Jboss Wildfly8 is used as Application Server.
Any Idea? or any working example?
This is because you put wrong path here:
var ws = new WebSocket("ws://localhost:8080/echo");
if your application is packed to eg: websocketapp.war (or if you set context-path on websocketapp)
then you should use:
var ws = new WebSocket("ws://localhost:8080/websocketapp/echo");
Connecting to web-socket For example
var webSocket= new WebSocket("ws://l92.168.1.27:50333/project name//serverendpointdemo");
var messagesTextArea=document.getElementsByClassId("messagesTextArea");
webSocket.onopen=function(message){processOpen(message);};
webSocket.onclose=function(message){processClose(message);};
webSocket.onmessage=function(message){processMessage(message);};
webSocket.onerror=function(message){processError(message);};
function processOpen(message){
messagesTextArea.value+="Server connected...."+"\n";
}
function processMessage(message){
messagesTextArea.value+="Received from server:...."+message.data+"\n";
}
Im trying to connect from a Java client i am writing to my nodejs sockjs server.
The sockjs server is just a simple echo server, taken from the examples on git:
var http = require('http');
var sockjs = require('sockjs');
var node_static = require('node-static');
// 1. Echo sockjs server
var sockjs_opts = {sockjs_url: "http://cdn.sockjs.org/sockjs-0.3.min.js"};
var sockjs_echo = sockjs.createServer(sockjs_opts);
sockjs_echo.on('connection', function(conn) {
conn.on('data', function(message) {
conn.write(message);
});
});
// 2. Static files server
var static_directory = new node_static.Server(__dirname);
// 3. Usual http stuff
var server = http.createServer();
server.addListener('request', function(req, res) {
static_directory.serve(req, res);
});
server.addListener('upgrade', function(req,res){
res.end();
});
sockjs_echo.installHandlers(server, {prefix:'/echo'});
console.log(' [*] Listening on 0.0.0.0:8080' );
server.listen(8080, '0.0.0.0');
Now i've tried to connect from my Java client with the following:
public static void connect() throws Exception {
final WebSocket ws = new WebSocket();
ws.addWebSocketListener(
new WebSocketAdapter() {
#Override
public void onMessage(WebSocketEvent messageEvent) {
System.out.println("Received Event Data: " + messageEvent.getData());
// let's close the open connection...
try {
ws.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onOpen(WebSocketEvent openEvent) {
System.out.println("Connection to Server is up!");
// we are able to talk to the WebSocket gateway
try {
ws.send("Hey, server!");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
);
ws.connect(new URI("ws://server.hello.com:8080/echo/websocket"));
}
The error i am getting when my java client tried to connect is:
com.kaazing.gateway.client.html5.impl.bridge.BridgeUtil
initCrossOriginProxy WARNING: Unable to connect: the Gateway may not
be running, a network route may be unavailable, or the Gateway may not
be configured properly
Any ideas what could be wrong?