Reputation: 605
I have a Java websocket that keeps sending a bunch of coordinates which I want to CONSTANTLY intercept from a js client. Here is a simplified version of the java code:
public static void main(String args[]) throws IOException {
final int portNumber = 2500;
System.out.println("Creating server socket on port " + portNumber);
ServerSocket serverSocket = new ServerSocket(portNumber);
while (true) {
Socket socket = serverSocket.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
pw.println("test");
pw.println("\r");
}
//later on close connection
pw.close();
socket.close();
}
As for my js code here is how it looks like:
var connection;
try{
connection = new MozWebSocket('ws://localhost:2500/');
}catch(e){
connection = new WebSocket('ws://localhost:2500/');
}
connection.onopen = function () {console.log('opened');};
connection.onclose = function(evt) { console.log("closed"); };
connection.onmessage = function(evt) { console.log("message"); };
connection.onerror = function(evt) { console.log(evt); };
After running this I get something like "Error during WebSocket handshake: No response code found in status line" and I understand that it's a difficult problem to overcome from a javascript client. Thus I'm wondering if I should rearrange the way I implemented the websocket or should I make a websocket server instead? But I am not sure if it will still allow me to constantly read the data my socket will be broadcasting at ALL TIMES. Thank you in advance.
Upvotes: 3
Views: 800
Reputation: 11474
You realize that websockets is a protocol right? It is not just sending plaintext.
I made an open source java webserver called Bowser that supports websockets. You can take a look at some of the code here for inspiration or just use the library: https://github.com/mirraj2/Bowser/tree/master/src/bowser/websocket
To start a websocket server, it is as simple as:
int port = 12345;
new WebSocketServer(port).onOpen(socket->{
System.out.println("Client connected: " + socket);
}).start();
Upvotes: 1