1、添加依赖
compile "org.java-websocket:Java-WebSocket:1.3.7"
2、编译MyWebsocket类继承WebSocketServer
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import android.os.Message;
import android.os.Handler;
public class MyWebSocket extends WebSocketServer {
public MyWebSocket(int port) {
super(new InetSocketAddress(port));
}
public MyWebSocket(InetSocketAddress address) {
super(address);
}
@Override
public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
System.out.println(webSocket.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!");
}
@Override
public void onClose(WebSocket webSocket, int i, String s, boolean b) {
System.out.println(webSocket + " onClose");
}
@Override
public void onMessage(WebSocket webSocket, String s) {
System.out.println(webSocket + ": " + s);
//收到消息转发到所有客户端
broadcast(s);
}
@Override
public void onError(WebSocket webSocket, Exception e) {
e.printStackTrace();
System.out.println("websocket erro"+e);
if (webSocket != null) {
// some errors like port binding failed may not be assignable to a specific websocket
}
}
@Override
public void onStart() {
System.out.println("Server started!");
}
}
3、编写客户端,这里使用javasctipt语言
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://"+window.location.hostname+":8887/websocket");
}
else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
};
//连接成功建立的回调方法
websocket.onopen = function () {
};
//接收到消息的回调方法
websocket.onmessage = function (event) {
let str=event.data;
console.log(str)
}
//连接关闭的回调方法
websocket.onclose = function () {
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
websocket.close();
}
//发送消息
function send(msg) {
websocket.send(msg);
}
4、启动服务
public static void main(String[] args) {
WebSocketImpl.DEBUG = true;
try {
int port = 8887; // 843 flash policy port
MyWebSocket s = new MyWebSocket(port);
s.start();
System.out.println("ChatServer started on port: " + s.getPort());
BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String in = sysin.readLine();
s.broadcast(in);
if (in.equals("exit")) {
s.stop(1000);
break;
}
System.out.println(" 客户端数据 "+in);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
网友评论