我有一个Spring Boot应用程序,可以处理文件上传和数据存储。我已经包含了WebSocket配置,但是WebSocket无法正常工作。我的Android应用程序抛出一个异常,说“流路径为空。
Handler类
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Component
public class SocketHandler extends TextWebSocketHandler {
List sessions = new ArrayList<>();
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws InterruptedException, IOException {
for(Object t : sessions) {
WebSocketSession webSocketSession = (WebSocketSession) t;
Map value = new Gson().fromJson(message.getPayload(), Map.class);
webSocketSession.sendMessage(new TextMessage("Hello " + value.get("name") + " !"));
}
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
//the messages will be broadcasted to all users.
sessions.add(session);
}
}
配置类
import com.labafrique.creporter.web.CReporterSpring.websocket.SocketHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
@Controller
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new SocketHandler(), "/t").setAllowedOrigins("*");
}
}
主班
import com.labafrique.creporter.web.CReporterSpring.controller.property.FileStorageProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@EnableJpaRepositories("com.labafrique.creporter.web.CReporterSpring.repository")
@EntityScan("com.labafrique.creporter.web.CReporterSpring.model")
@ComponentScan(basePackages = {"com.labafrique.creporter.web.CReporterSpring.controller"})
@EnableConfigurationProperties({
FileStorageProperties.class
})
@SpringBootApplication
public class CReporterSpringApplication {
public static void main(String[] args) {
SpringApplication.run(CReporterSpringApplication.class, args);
}
}
我曾尝试过在不同的软件包中移动类,但是仍然没有任何效果。