我希望能够从Java
代码向WebSocket发送消息。
这是WebSocket的配置类。
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
private WebSocketHandler handler;
public WebSocketConfig(WebSocketHandler handler) {
this.handler = handler;
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
webSocketHandlerRegistry.addHandler(this.handler, "/ws");
}
}
这是一个
websocket
处理程序。@Component
public class WebSocketHandler extends TextWebSocketHandler {
private static final Logger LOGGER = JavaLogUtils.getLogger();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
super.afterConnectionEstablished(session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
LOGGER.info(" Server >>>> {}", message);
session.sendMessage(message);
}
}
当我通过
JavaScript
在HTML
页面上发送消息时,可以像这样操作:$(function(){
var connection = new WebSocket('ws://localhost:8080/ws');
connection.onopen = function () {
console.log('Connected...');
};
connection.onmessage = function(event){
console.log('>>>>> ' + event.data);
var json = JSON.parse(event.data);
$("#output").append("<span><strong>" + json.user + "</strong>: <em>" + json.message +"</em></span><br/>");
};
connection.onclose = function(event){
$("#output").append("<p class=\"text-uppercase\"><strong>CONNECTION: CLOSED</strong></p>");
};
$("#send").click(function(){
var message = {}
message["user"] = $("#user").val();
message["message"] = $("#message").val();
connection.send(JSON.stringify(message));
});
});
这个功能很好用。但是当我尝试从Java客户端
发送消息时,它失败了。
@SpringBootApplication
@ComponentScan("com.lapots.breed.platform.cloud.boot")
@EnableJpaRepositories("com.lapots.breed.platform.cloud.boot.repository")
@EntityScan("com.lapots.breed.platform.cloud.boot.domain")
@EnableAspectJAutoProxy
@EnableJms
public class JavaCloudSampleApplication {
public static void main(String[] args) {
SpringApplication.run(JavaCloudSampleApplication.class, args);
}
@Bean
public CommandLineRunner welcomeSocketMessage(WebSocketHandler handler) throws URISyntaxException {
return args -> {
StandardWebSocketClient client = new StandardWebSocketClient();
ListenableFuture<WebSocketSession> future = client.doHandshake(handler,
new WebSocketHttpHeaders(),
new URI("ws://localhost:8080/ws"));
WebSocketSession session = future.get();
WebSocketMessage<String> message = new TextMessage("Hello from Spring");
session.sendMessage(message);
};
}
}
我遇到了这个错误
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) [surefire-junit4-2.20.jar:2.20]
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:272) [surefire-junit4-2.20.jar:2.20]
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:236) [surefire-junit4-2.20.jar:2.20]
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:159) [surefire-junit4-2.20.jar:2.20]
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:386) [surefire-booter-2.20.jar:2.20]
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:323) [surefire-booter-2.20.jar:2.20]
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:143) [surefire-booter-2.20.jar:2.20]
Caused by: java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:735) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:716) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:703) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:304) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) ~[spring-boot-test-1.5.6.RELEASE.jar:1.5.6.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE]
... 26 common frames omitted
Caused by: java.util.concurrent.ExecutionException: javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed
at java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[na:1.8.0_121]
at java.util.concurrent.FutureTask.get(FutureTask.java:192) ~[na:1.8.0_121]
at com.lapots.breed.platform.cloud.boot.JavaCloudSampleApplication.lambda$welcomeSocketMessage$4(JavaCloudSampleApplication.java:76) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
... 32 common frames omitted
Caused by: javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:395) ~[tomcat-embed-websocket-8.5.16.jar:8.5.16]
at org.springframework.web.socket.client.standard.StandardWebSocketClient$1.call(StandardWebSocketClient.java:150) ~[spring-websocket-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at org.springframework.web.socket.client.standard.StandardWebSocketClient$1.call(StandardWebSocketClient.java:147) ~[spring-websocket-4.3.10.RELEASE.jar:4.3.10.RELEASE]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_121]
at java.lang.Thread.run(Thread.java:745) ~[na:1.8.0_121]
Caused by: java.util.concurrent.ExecutionException: java.io.IOException: The remote computer refused the network connection.
at sun.nio.ch.PendingFuture.get(PendingFuture.java:202) ~[na:1.8.0_121]
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:336) ~[tomcat-embed-websocket-8.5.16.jar:8.5.16]
... 4 common frames omitted
Caused by: java.io.IOException: The remote computer refused the network connection.
at sun.nio.ch.Iocp.translateErrorToIOException(Iocp.java:309) ~[na:1.8.0_121]
at sun.nio.ch.Iocp.access$700(Iocp.java:46) ~[na:1.8.0_121]
at sun.nio.ch.Iocp$EventHandlerTask.run(Iocp.java:399) ~[na:1.8.0_121]
... 1 common frames omitted
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 8.071 s <<< FAILURE! - in com.lapots.breed.platform.cloud.boot.app.JavaCloudSampleApplicationTests
[ERROR] contextLoads(com.lapots.breed.platform.cloud.boot.app.JavaCloudSampleApplicationTests) Time elapsed: 0 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: java.lang.IllegalStateException: Failed to execute CommandLineRunner
Caused by: java.util.concurrent.ExecutionException: javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed
Caused by: javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed
Caused by: java.util.concurrent.ExecutionException:
java.io.IOException: The remote computer refused the network connection.
Caused by: java.io.IOException:
The remote computer refused the network connection.