网站制作平台,阿里云 wordpress rds,阿里云免费空间,企业咨询服务是做什么的WebSocket是一种在单个TCP连接上进行全双工通信的协议#xff0c;其设计的目的是在Web浏览器和Web服务器之间进行实时通信#xff08;实时Web#xff09;。
WebSocket协议的优点包括#xff1a;
1. 更高效的网络利用率#xff1a;与HTTP相比#xff0c;WebSocket的握手…WebSocket是一种在单个TCP连接上进行全双工通信的协议其设计的目的是在Web浏览器和Web服务器之间进行实时通信实时Web。
WebSocket协议的优点包括
1. 更高效的网络利用率与HTTP相比WebSocket的握手只需要一次之后客户端和服务器端可以直接交换数据
2. 实时性更高WebSocket的双向通信能够实现实时通信无需等待客户端或服务器端的响应
3. 更少的通信量和延迟WebSocket可以发送二进制数据而HTTP只能发送文本数据并且WebSocket的消息头比HTTP更小。
简单使用示例
1. 客户端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);
2. 服务器端Java代码
java
import 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 SetWebSocket webSockets new HashSet();public static void main(String[] args) throws IOException {//创建ServerSocketServerSocket 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();}}}
}
3. 服务器端WebSocket代码
java
import 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());}Overridepublic 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();}}}
}