2

I was wondering if anyone is aware of tutorial/resource to learn how to connect to a websocket server using a JAVA application, instead of html5. I've been searching and can't find anything as they all give a server websocket example in java but client side in html5.

I know you can do http GET/POST in java, so I was wondering what step I would need to enable websockets via java based console app, vs html5.

try{
connection = (HttpURLConnection)serverAddress.openConnection();
conection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(1000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStreamReader()));
sb = new StringBuilder();

while((line=reader.readLine())!=null){
sb.append("Recieved: "+line+"\n");
}

}catch(Exception e){e.printStackTrace();
}finally{
connection.disconnect();
reader = null;
sb=null;
connection=null;

}

how can I turn this method here into a websocket connection?

1 Answer 1

3

Take a look at the Java EE 7 WebSocket API. It has a javax.websocket.WebSocketContainer class which has a connectToServer() method that accepts a ClientEndpoint. I haven't used a Java client myself so I don't have any sample code, but if you search for examples with those classes and method you might find something.

[edit] some links:

To be fair - there is plenty of other implementations, you can take a look at Tomcat or Jetty.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.