Environment: jdk.18 tomcat-7.0.70
Put Tomcat in the
Two Jir packets copied to
Note: To remove these two jar packages when the last deployment is already in tomcate.
Ebsocket object creation and server connection
To connect the communication endpoint, simply create a new WebSocket instance and provide the peer URL you want to connect to.
The ws://and wss://prefixes represent websocket connections and secure websocket connections, respectively.
url = "Ws://localhost:8080/echo";
w = new WebSocket (URL);
When establishing a websocket connection, you can list the protocols that the Web app can use
varWs;window.onload=function() {ws=NewWebSocket ("Ws://192.168.32.132:8080/cainiaotv/websocket"); Ws.onopen=function(){ };} Document.onkeydown=function(event) {varE = Event | | window.event | | Arguments.callee.caller.arguments[0]; if(e && E.keycode = = 13) {sendmsg (); }}; functionsendmsg () {/** Ws.onopen = function () {};*/ vartxt = "xxx"; /** * Send Message*/ if(txt.length>0) {ws.send (TXT); }Else{alert ("Please enter text"); } /** * Receive the returned message*/Ws.onmessage=function(evt) {varReceived_msg =Evt.data; Console.log (RECEIVED_MSG); }; /** * Close connection*/Ws.onclose=function() { }; }
Background:
Package Com.cainiao.tv.servlet;import Java.util.set;import Javax.websocket.endpoint;import Javax.websocket.server.serverapplicationconfig;import javax.websocket.server.serverendpointconfig;/** * WebSocket * @author Administrator * */public class Talksocket implements Serverapplicationconfig {/** * Annotated way to start * Automatically scan local websocket * @return Scan is websocket */@Overridepublic set<class<?>> getannotatedendpointclasses (set<class<? >> scan) {//TODO auto-generated method Stubreturn scan;} /** * Interface Mode start */@Overridepublic set<serverendpointconfig> getendpointconfigs (set<class<? extends Endpoint >> arg0) {//TODO auto-generated method Stubreturn null;}}
Importjava.io.IOException;Importjava.util.List;ImportJavax.websocket.OnClose;ImportJavax.websocket.OnMessage;ImportJavax.websocket.OnOpen;Importjavax.websocket.Session;ImportJavax.websocket.server.ServerEndpoint;ImportCom.cainiao.tv.entity.Talk;Importcom.cainiao.tv.entity.User_Tv; @ServerEndpoint ("/websocket") Public classTalkwebsocketserver {Private Staticlist<session> sessions =New@OnOpen Public voidOpen (Session session) {Sessions.add (session); } Public voidBroadcast (list<session>sessions,string msg) { for(Iterator iter =sessions.iterator (); Iter.hasnext ();) {Session session=(Session) iter.next (); Try{session.getbasicremote (). SendText (msg); } Catch(IOException e) {e.printstacktrace (); } }} @OnMessage Public voidmessgae (Session session,string msg) {System.out.println ("Message content:" +msg); Broadcast ( This. sessions,msg)//Broadcast} @OnClose Public voidClose (Session session) {}}
WebSocket-based JSP interacts with Java