Reputation: 177
So, i have this Java Aplication that returns me a few data. This data is printed in a TXT and is saved on my PC.
I want to send this information via Socket instead save in TXT. (Example below)
Java
public static void main(String argv[]) throws Exception { Socket clientSocket = new Socket(); SocketAddress sockaddr = new InetSocketAddress("localhost", 3000); clientSocket.connect(sockaddr); clientSocket.close(); }
Node JS
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); io.on('connection', function(socket){ console.log('a user connected'); socket.on('disconnect', function(){ console.log('user disconnected'); }); }); io.on('connection', function(socket){ socket.on('chat message', function(msg){ console.log(msg); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); });
The problem is, the Java Class connect the NodeJS server. (I'm using socket.io) But NodeJS is not recognizing the Java connection.
Does anyone knows why this is happening/ knows another way to do this?
Upvotes: 1
Views: 2122
Reputation: 708026
Can i communicate JAVA to Javascript using Sockets?
Yes and no. Yes, you can communicate from Java to Javascript using socket.io. No, you cannot use a plain TCP socket in Java to talk to a socket.io server. You need to have a socket.io client (with the whole protocol and connection scheme it uses) to talk to a socket.io server.
Your node.js app is configuring a socket.io server. That is a webSocket server that adds some additional socket.io format on top of the webSocket packets.
Your Java server is a plain TCP connection and that will not work with a socket.io server. You Java server must be a socket.io client in order to talk to a socket.io server. It has to speak the right protocol in order to communicate.
You can get a Java class for a socket.io client and then it should be able to connect to your socket.io server correctly.
Keep in mind that socket.io is a layer on top of the webSocket protocol so your Java client has to speak both of those layers in order to communicate with your nodejs socket.io server. If you want to see what a webSocket connection looks like, see this article. It starts with an http request, with an upgrade header and some security headers. The server then responds a certain way telling the client that the protocol can then be upgraded from the http protocol to the webSocket protocol. Socket.io, then has a data format on top of this. You shouldn't have to implement this yourself from scratch since there are already socket.io client classes for Java.
Upvotes: 2