java代码
package leitao.zhang; import java.io.IOException; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; /** * * 注意事项: * 1.需要用 @ServerEndpoint(value="/wb") 注解来指定请求路径 * 2.必须有: * 1.方法必须是public * 2.必须没有返回值 * 3.方法必须使用注解 * 4.方法的参数必须争取 * * @OnOpen * public void onOpen(Session session) * @OnMessage * public void onMessage(String message,Session session) * @OnClose * public void onClose() * @OnError * public void onError() * @author wiwide.leitao.zhang * * */ @ServerEndpoint(value="/wb") public class WebSocketTest{ @OnOpen public void onOpen(Session session) { System.out.println("连接进入"); } @OnMessage public void onMessage(String message,Session session) { try { session.getBasicRemote().sendText("接受到消息"+message); } catch (IOException e) { e.printStackTrace(); } } @OnClose public void onClose() { } @OnError public void onError(Session session, Throwable error) { } }
HTML5代码
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <script type="text/javascript"> // 打开一个 web socket var ws = new WebSocket("ws://localhost:8000/websocketdemo2/wb"); ws.onopen = function() { console.log("链接已打开"); ws.send("hhhhhaadad"); }; ws.onmessage = function (evt) { console.log("数据已接收...",evt); }; ws.onclose = function() { // 关闭 websocket console.log("连接已关闭..."); }; </script> </body> </html>
未经允许不得转载:开心乐窝-乐在其中 » java版 webScoket