js使用WebSocket,java使用WebSocket
js使用WebSocket,java使用WebSocket
创建java服务端代码
import java.net.InetSocketAddress; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketImpl; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; public class MyWebSocket extends WebSocketServer{ public static void main(String[] args) { WebSocketImpl.DEBUG = false; int port = 8887; //端口 MyWebSocket s = new MyWebSocket(port); s.start(); System.out.println( "服务器的端口" + s.getPort() ); } public MyWebSocket(int port){ super(new InetSocketAddress(port)); } public MyWebSocket(InetSocketAddress address) { super(address); } /** * 关闭时触发的事件 */ @Override public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) { // TODO Auto-generated method stub } /** * 发生错误时 */ @Override public void onError(WebSocket arg0, Exception arg1) { System.out.println(arg1); } /** * 收到消息时 */ @Override public void onMessage(WebSocket arg0, String arg1) { arg0.send("123"); System.out.println(arg1); } /** * 打开连接时 */ @Override public void onOpen(WebSocket arg0, ClientHandshake arg1) { System.out.println(1234455); } }
编写html页面代码
if("WebSocket" in window){ console.log("您的浏览器支持WebSocket"); let a=new WebSocket(encodeURI(\'ws://127.0.0.1:8887\')); a.onopen=function(){ a.send("123aa"); } a.onopen=function(){ a.send("123aabbbb"); } a.onmessage=function(msg){ console.log(msg.data); } }else{ console.log("您的浏览器不支持WebSocket"); }
版权声明:本文为qq376324789原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。