基于websocket的jsp与java进行交互
环境:jdk.18 tomcat-7.0.70
把tomcat中的
两个jir包复制到
注意:最后部署的时候要删除掉这两个jar包 tomcate中已经有了
ebSocket对象的创建和服务器连接
要连接通信端点,只需要创建一个新的WebSocket实例,并提供希望连接的对端URL。
ws://和wss://前缀分别表示WebSocket连接和安全的WebSocket连接。
url = "ws://localhost:8080/echo";
w = new WebSocket(url);
建立WebSocket连接时,可以列出Web应用能够使用的协议
var ws; window.onload=function(){ ws = new WebSocket("ws://192.168.32.132:8080/CaiNiaoTV/websocket"); ws.onopen=function(){ }; } document.onkeydown=function(event){ var e = event || window.event || arguments.callee.caller.arguments[0]; if (e && e.keyCode == 13) { sendMsg(); } }; function sendMsg(){ /* * ws.onopen = function() { }; */ var txt = "xxx"; /** * 发送消息 */ if(txt.length>0){ ws.send(txt); }else{ alert("请输入文字"); } /** * 接收返回的消息 */ ws.onmessage = function (evt) { var received_msg = evt.data; console.log(received_msg); }; /** * 关闭连接 */ ws.onclose = function() { }; }
后台:
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 { /** * 注解的方式启动 * 自动扫描本地的websocket * @return scan是websocket */ @Override public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scan) { // TODO Auto-generated method stub return scan; } /** * 接口方式启动 */ @Override public Set<ServerEndpointConfig> getEndpointConfigs( Set<Class<? extends Endpoint>> arg0) { // TODO Auto-generated method stub return null; } }
import java.io.IOException; import java.util.List; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import com.cainiao.tv.entity.Talk; import com.cainiao.tv.entity.User_Tv; @ServerEndpoint("/websocket") public class TalkWebSocketServer { private static List<Session> sessions = new @OnOpen public void open(Session session){ sessions.add(session); } public void broadcast(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 void messgae(Session session,String msg){ System.out.println("消息内容:"+msg); broadcast(this.sessions,msg)//广播 } @OnClose public void close(Session session){ } }