Wednesday, 15 June 2011

java - Tomcat clientendpoint websocket keeps closing -



java - Tomcat clientendpoint websocket keeps closing -

i have next clientendpoint class websocket in tomcat 7.0.53. based off of illustration on website https://blog.openshift.com/how-to-build-java-websocket-applications-using-the-jsr-356-api/

import java.io.ioexception; import java.net.uri; import java.util.arraylist; import javax.websocket.clientendpoint; import javax.websocket.closereason; import javax.websocket.containerprovider; import javax.websocket.deploymentexception; import javax.websocket.onclose; import javax.websocket.onerror; import javax.websocket.onmessage; import javax.websocket.onopen; import javax.websocket.session; import javax.websocket.websocketcontainer; @clientendpoint public class connect { private static arraylist<session> sessionlist = new arraylist<session>(); public connect(uri endpointuri) throws deploymentexception, ioexception { websocketcontainer container = containerprovider.getwebsocketcontainer(); container.connecttoserver(this, endpointuri); } @onopen public void onopen(session session) throws ioexception { sessionlist.add(session); system.out.println(session.getid()); session.getbasicremote().sendtext("hello"); } public void sendmessage(string message) throws ioexception { for(session session : sessionlist){ //asynchronous communication session.getbasicremote().sendtext(message); } } @onclose public void onclose(session session){ sessionlist.remove(session); system.out.println("here"); } @onerror public void onerror(throwable t, session session){ system.out.println("tedt"); } }

i have next code start client endpoint

import java.io.ioexception; import java.net.uri; import java.net.urisyntaxexception; import javax.websocket.deploymentexception; public class test { public static void main(string[] args) throws deploymentexception, ioexception, urisyntaxexception { // todo auto-generated method stub connect connect = new connect(new uri("ws://localhost:8080/example/talk")); connect.sendmessage("now"); } }

the client connect websocket server, gets disconnected right away when seek send message or anything, know since onerror function beingness called when seek send message onopen function. why websocket getting closed after connected server?

you beingness disconnected because main thread in client application ending. after send "now", programme exits. if want else (like wait response server, instance), you'll have prevent main thread exiting. seek @ end of main method:

system.in.read();

this cause process sit down , wait input standard input. wait test finish , press come in on command-line terminate client.

you will, of course, want register handler receiving messages server client. right now, can send messages client server.

java tomcat websocket client-server tomcat7

No comments:

Post a Comment