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?
Related
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;
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 created a new verticle that should response for HTTP requests and SockJS bridged events. Based on this question https://stackoverflow.com/questions/41516328 and vert.x manual https://vertx.io/docs/vertx-web/java/#_sockjs I created this piece of code:
Java:
#Override
public void start(Future<Void> startFuture) throws Exception {
startHttpServer(startFuture);
startSockJSHandler();
}
private void startHttpServer(Future<Void> startFuture) {
HttpServer server = vertx.createHttpServer(new HttpServerOptions());
server.requestHandler(req -> {
System.out.println("[" + new Date().toString() + "] Request #" + ++requestCount);
if (req.path().contains("http")) {
req.response().putHeader("Access-Control-Allow-Origin", "*").end("req_num: " + requestCount);
}
}).listen(8080, ar -> startFuture.handle(ar.mapEmpty()));
}
private void startSockJSHandler() {
Router router = Router.router(vertx);
SockJSHandlerOptions sockJSOptions = new SockJSHandlerOptions().setHeartbeatInterval(2000);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx, sockJSOptions);
BridgeOptions bridgeOptions = new BridgeOptions();
bridgeOptions.addInboundPermitted(new PermittedOptions().setAddressRegex(".*")).addOutboundPermitted(new PermittedOptions().setAddressRegex(".*"));
sockJSHandler.bridge(bridgeOptions, be -> {
System.out.println("BRIDGE EVENT: " + be.type().toString());
});
router.route("/eventbus/*").handler(sockJSHandler);
}
JavaScript eventbus client:
var sock = new SockJS('http://localhost:8080/eventbus/');
sock.onopen = function() {
console.log('open');
sock.send('test');
};
sock.onmessage = function(e) {
console.log('message', e.data);
sock.close();
};
sock.onclose = function() {
console.log('close');
};
HTTP request/response works fine, but SockJS events not. In web browser 'Network' module I see only one SockJS request (http://localhost:8080/eventbus/info). 8 seconds in 'pending' status, and after this time the status is changed to 'closed' (method onclose() is called at the end).
Did I do something wrong?
The HttpServer must delegate requests to the Router. Otherwise nothing happens. Usually, it is configured to delegate all requests to the Router.
server.requestHandler(router::accept).listen(8080);
See Basic Vert.x-Web concepts in the docs.
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";
}
I am implementing a Java program,
which has to connect to remote server
connected remote server should download a file from ftp
i am using Apache MINA lib's for this code
here is code, which connects to the remote server
public class filetrans
{
public static void main(String[] args) throws IOException, InterruptedException
{
SshClient client = null;
String login="user";
String password="password";
try
{
client = SshClient.setUpDefaultClient();
client.start();
ConnectFuture future = client.connect("myhost",myport);
future.await();
ClientSession session = (ClientSession) future.getSession();
boolean auth = session.authPassword(login, password).await().isSuccess();
if (auth)
{
System.out.println("Authenticated....");
ClientChannel channel = session.createChannel("shell");
channel.setIn(new NoCloseInputStream(System.in));
channel.setOut(new NoCloseOutputStream(System.out));
channel.setErr(new NoCloseOutputStream(System.err));
channel.open();
channel.waitFor(ClientChannel.CLOSED, 5000);
channel.close(true);
}
else
{
System.out.println("Authentication failed....");
}
}
catch (Throwable t)
{
System.out.println(t);
}
finally
{
client.stop();
}
}
}
I am successfully connecting to the Remote server. now i have to connect to the FTP server and download a file and to save in the Remote Server. I am Stuck here, any ideas how to implement further or any codes or any suggestion will be great. thanks