PDA

View Full Version : Java server javascript client websockets



agfac
Jan 4th, 2017, 08:03 PM
I'm trying to do a connection between a server in Java and a Javascript client but I'm getting this error on server side:

WebSocket connection to 'ws://127.0.0.1:4444/' failed: Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE

Could someone help me please?

Thanks

Server


import java.io.IOException;
import java.net.ServerSocket;

public class Server {

public static void main(String[] args) throws IOException {

try (ServerSocket serverSocket = new ServerSocket(12000)) {
GameProtocol gp = new GameProtocol();

ServerThread player= new ServerThread(serverSocket.accept(), gp);
player.start();

} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}

}

}


ServerThread


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerThread extends Thread{

private Socket socket = null;
private GameProtocol gp;

public ServerThread(Socket socket, GameProtocol gp) {
super("ServerThread");
this.socket = socket;
this.gp = gp;
}

public void run() {

try (
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
) {
String inputLine, outputLine;

//outputLine = gp.processInput(null);
//System.out.println(outputLine);
//out.println(outputLine);

while ((inputLine = in.readLine()) != null) {
//System.out.println(outputLine);
outputLine = gp.processInput(inputLine);
System.out.println(outputLine);
out.println(outputLine);
/*if (outputLine.equals("Bye"))
break;*/
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


GameProtocol



public class GameProtocol {

public String processInput(String theInput) {

String theOutput = null;

theOutput = theInput;

return theOutput;
}
}


Client


var connection = new WebSocket('ws://127.0.0.1:12000');

connection.onopen = function () {
connection.send('Ping'); // Send the message 'Ping' to the server
};

// 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);
};