maven
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
java代码
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.StandardWebSocketClient;
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.standard.StandardWebSocketSession;
import org.springframework.web.socket.client.standard.StandardWebSocketSessionHandshake;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
public class ChatWebSocketClient extends TextWebSocketHandler {
private StandardWebSocketSession session;
public void connect() throws IOException {
WebSocketClient client = new StandardWebSocketClient();
WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
URI uri = URI.create("ws://localhost:8080/ws/chat");
StandardWebSocketSessionHandshake handshake = new StandardWebSocketSessionHandshake(client, headers, new HttpHeaders(), uri);
session = (StandardWebSocketSession) handshake.doHandshake(new TextWebSocketHandler());
session.open();
}
@Override
public void afterConnectionEstablished(StandardWebSocketSession session) throws Exception {
System.out.println("WebSocket connection established.");
}
@Override
protected void handleTextMessage(StandardWebSocketSession session, TextMessage message) throws Exception {
System.out.println("Received: " + message.getPayload());
}
public void sendMessage(String message) throws IOException {
session.sendMessage(new TextMessage(message));
}
public void close() throws IOException {
session.close();
}
public static void main(String[] args) throws IOException, InterruptedException {
ChatWebSocketClient client = new ChatWebSocketClient();
client.connect();
client.sendMessage("Hello, WebSocket!");
Thread.sleep(2000); // Wait for the echo message
client.close();
}
}