您还必须在 Spring 配置中的 Bean 中添加 TestSocket 并configurator = SpringConfigurator.class
从您的 TestSocket 中删除。
通常 Spring 通过它的 STOMP 协议覆盖普通的 java JSR 356 websocket,它是 websocket 的一部分。它也不像普通的 websocket 那样支持完全二进制消息。您应该将ServerEndpointExporter
配置添加为:
@Configuration
public class EndpointConfig
{
@Bean
public ChatEndpointNew chatEndpointNew(){
return new ChatEndpointNew();
}
@Bean
public ServerEndpointExporter endpointExporter(){
return new ServerEndpointExporter();
}
}
让我们看看客户端 ge 连接的房间的完整聊天消息:
@ServerEndpoint(value="/chatMessage/{room}")
public class ChatEndpointNew
{
private final Logger log = Logger.getLogger(getClass().getName());
@OnOpen
public void open(final Session session, @PathParam("room")final String room)
{
log.info("session openend and bound to room: " + room);
session.getUserProperties().put("room", room);
System.out.println("session openend and bound to room: " + room);
}
@OnMessage
public void onMessage(final Session session, final String message) {
String room = (String)session.getUserProperties().get("room");
try{
for (Session s : session.getOpenSessions()){
if(s.isOpen()
&& room.equals(s.getUserProperties().get("room"))){
String username = (String) session.getUserProperties().get("username");
if(username == null){
s.getUserProperties().put("username", message);
s.getBasicRemote().sendText(buildJsonData("System", "You are now connected as:"+message));
}else{
s.getBasicRemote().sendText(buildJsonData(username, message));
}
}
}
}catch(IOException e) {
log.log(Level.WARNING, "on Text Transfer failed", e);
}
}
@OnClose
public void onClose(final Session session){
String room = (String)session.getUserProperties().get("room");
session.getUserProperties().remove("room",room);
log.info("session close and removed from room: " + room);
}
private String buildJsonData(String username, String message) {
JsonObject jsonObject = Json.createObjectBuilder().add("message", "<tr><td class='user label label-info'style='font-size:20px;'>"+username+"</td>"+"<td class='message badge' style='font-size:15px;'> "+message+"</td></tr>").build();
StringWriter stringWriter = new StringWriter();
try(JsonWriter jsonWriter = Json.createWriter(stringWriter)){
jsonWriter.write(jsonObject);
}
return stringWriter.toString();
}
}
请注意,您应该将 ChatEndpointNew 和 ServerEndpointExporter 分别添加到应用程序的主要 Spring 配置中。如果出现任何错误,请尝试以下操作:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
您还可以浏览此Spring 文档。