WebSocket是一种在单个TCP连接上进行全双工通信的协议,其设计的目的是在Web浏览器和Web服务器之间进行实时通信(实时Web)。
WebSocket协议的优点包括:
-
更高效的网络利用率:与HTTP相比,WebSocket的握手只需要一次,之后客户端和服务器端可以直接交换数据;
-
实时性更高:WebSocket的双向通信能够实现实时通信,无需等待客户端或服务器端的响应;
-
更少的通信量和延迟:WebSocket可以发送二进制数据,而HTTP只能发送文本数据,并且WebSocket的消息头比HTTP更小。
简单使用示例:
-
客户端JavaScript代码:
javascript//创建WebSocket对象 var socket = new WebSocket("ws://localhost:8080/"); //建立连接后回调函数 socket.onopen = function(event) { console.log("WebSocket连接建立成功"); }; //接收到消息后回调函数 socket.onmessage = function(event) { console.log("接收到消息:" + event.data); }; //错误回调函数 socket.onerror = function(event) { console.log("WebSocket连接发生错误"); }; //关闭回调函数 socket.onclose = function(event) { console.log("WebSocket连接关闭"); }; //发送消息 socket.send("hello server");
-
服务器端Java代码:
javaimport java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.HashSet; import java.util.Set; public class WebSocketServer { //存储所有连接到服务器的WebSocket对象 private static Set<WebSocket> webSockets = new HashSet<>(); public static void main(String[] args) throws IOException { //创建ServerSocket ServerSocket serverSocket = new ServerSocket(8080); System.out.println("服务器已启动,监听端口:8080"); //循环等待客户端连接 while (true) { //创建Socket对象 Socket socket = serverSocket.accept(); //创建WebSocket对象,存储到集合中 WebSocket webSocket = new WebSocket(socket); webSockets.add(webSocket); //启动线程,处理该WebSocket连接 new Thread(webSocket).start(); System.out.println("客户端已连接:" + socket.getInetAddress().getHostAddress()); } } //广播消息给所有连接到服务器的WebSocket对象 public static void broadcast(String message) { for (WebSocket webSocket : webSockets) { try { webSocket.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } }
-
服务器端WebSocket代码:
javaimport java.io.IOException; import java.io.InputStream; import java.net.Socket; public class WebSocket implements Runnable { private Socket socket; private InputStream inputStream; public WebSocket(Socket socket) throws IOException { this.socket = socket; this.inputStream = socket.getInputStream(); } //接收消息 public String receiveMessage() throws IOException { byte[] buffer = new byte[1024]; int len = inputStream.read(buffer); return new String(buffer, 0, len); } //发送消息 public void sendMessage(String message) throws IOException { socket.getOutputStream().write(message.getBytes()); } @Override public void run() { try { while (true) { String message = receiveMessage(); System.out.println("接收到消息:" + message); WebSocketServer.broadcast(message); } } catch (IOException e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }