1. 使用JSON格式传输参数
可以使用库如Jackson或Gson来处理JSON。
客户端发送JSON消息:
javascript
var socket = new WebSocket("ws://localhost:8080/ws");
socket.onopen = function() {
var message = {
"action": "greet",
"name": "Alice"
};
socket.send(JSON.stringify(message));
};
服务器端解析JSON消息:
java
import com.fasterxml.jackson.databind.ObjectMapper; // Jackson库
// ... 在WebSocket的handler中
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(message.getPayload());
String action = jsonNode.get("action").asText();
String name = jsonNode.get("name").asText();
// 根据解析的参数执行相应操作
if ("greet".equals(action)) {
String response = "Hello, " + name + "!";
session.sendMessage(new TextMessage(response));
}
}
2. 使用查询参数式格式传输
客户端发送查询参数式消息:
javascript
var socket = new WebSocket("ws://localhost:8080/ws");
socket.onopen = function() {
socket.send("action=greet&name=Alice");
};
服务器端解析查询参数式消息:
java
// ... 在WebSocket的handler中
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String[] params = message.getPayload().split("&");
Map<String, String> paramMap = new HashMap<>();
for (String param : params) {
String[] keyValue = param.split("=");
paramMap.put(keyValue[0], keyValue[1]);
}
String action = paramMap.get("action");
String name = paramMap.get("name");
// 处理逻辑...
}
3. 使用XML格式传输参数
虽然XML相对于JSON更为冗长,但在某些情况下,它可能更为适合,特别是当消息结构复杂或需要与遗留系统集成时。
客户端发送XML消息:
javascript
var socket = new WebSocket("ws://localhost:8080/ws");
socket.onopen = function() {
var xmlString = '<message><action>greet</action><name>Alice</name></message>';
socket.send(xmlString);
};
服务器端解析XML消息:
java
import javax.xml.parsers.DocumentBuilder; // Java内置的XML解析器
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
// ... 在WebSocket的handler中
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(message.getPayload())));
String action = doc.getElementsByTagName("action").item(0).getTextContent();
String name = doc.getElementsByTagName("name").item(0).getTextContent();
// 处理逻辑...
}