目前node.js 有大量的websocket库,最流行的似乎是:
然而,我找不到任何一个之间的任何具体的具体比较...显然Socket.io很棒,但已经过时了,并且已经失败了.ws和websocket-node都声称它们是最快的.而engine.io似乎是新的,但比较轻的aletarntives重得多.
如果我们或某人能够将一个答案作为指导,使用哪个套接字库以及何时使用它们,以及它们之间的比较,那将是惊人的.
我正在使用包含STOMP/SockJS WebSocket的Spring Boot(1.3.0.BUILD-SNAPSHOT)设置RESTful Web应用程序,我打算从iOS应用程序和Web浏览器中使用它.我想使用JSON Web令牌(JWT)来保护REST请求和WebSocket接口,但我对后者有困难.
该应用程序使用Spring Security进行保护: -
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
public WebSecurityConfiguration() {
super(true);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("steve").password("steve").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling().and()
.anonymous().and()
.servletApi().and()
.headers().cacheControl().and().and()
// Relax CSRF on the WebSocket due to needing direct access from apps
.csrf().ignoringAntMatchers("/ws/**").and()
.authorizeRequests()
//allow anonymous resource requests
.antMatchers("/", "/index.html").permitAll()
.antMatchers("/resources/**").permitAll()
//allow anonymous POSTs to JWT
.antMatchers(HttpMethod.POST, "/rest/jwt/token").permitAll()
// Allow anonymous …Run Code Online (Sandbox Code Playgroud) 我有,我认为是一个非常简单的Spring WebSocket应用程序.但是,我正在尝试使用路径变量进行订阅以及消息映射.
我在下面发布了一个释义的例子.我希望@SendTo注释能够根据用户返回给订阅者fleetId.即POST以/fleet/MyFleet/driver/MyDriver应通知用户/fleet/MyFleet,但我没有看到这种行为.
值得注意的是订阅文字/fleet/{fleetId}作品.这是有意的吗?我错过了一些配置吗?或者这不是它的工作原理吗?
我对WebSockets或Spring项目不是很熟悉,所以提前谢谢.
Controller.java
...
@MessageMapping("/fleet/{fleetId}/driver/{driverId}")
@SendTo("/topic/fleet/{fleetId}")
public Simple simple(@DestinationVariable String fleetId, @DestinationVariable String driverId) {
return new Simple(fleetId, driverId);
}
...
Run Code Online (Sandbox Code Playgroud)
WebSocketConfig.java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/live");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/fleet").withSockJS();
}
}
Run Code Online (Sandbox Code Playgroud)
的index.html
var socket = new SockJS('/fleet');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
// Doesn't Work
stompClient.subscribe('/topic/fleet/MyFleet', …Run Code Online (Sandbox Code Playgroud) 我最近遇到了关于内存泄漏和扩展问题的Socket.io问题.我决定使用Socket.io是在一年前做出来的,当时它无疑是最好的库.
既然Socket.io造成了很多麻烦,我花时间寻找在此期间可用的替代品,并认为Engine.io和SockJS通常都适合我.但是,在我看来,两者都有一些缺点,我不确定选择哪一个.
Engine.io基本上是Socket.io的完美轻量级版本,它不包含我不需要的所有功能.我已经为Socket.io编写了自己的重新连接和心跳逻辑,因为我对默认逻辑不满意,我从不打算使用Socket.io提供的房间或其他功能.
但是 - 在我看来 - Engine.io的主要缺点是建立连接的方式.客户端以较慢的jsonp-polling开始,如果它们支持更好的传输,则会升级.该支持WebSockets的原生(数量不断增加)的客户有超过那些使用过时的浏览器客户更长的和不稳定的连接过程的形式不利的事实,违背我的,应该如何处理的感觉.
另一方面,SockJS完全按照我的意愿处理连接.根据我的阅读,它似乎相当稳定,而Engine.io目前有一些问题.
我的应用程序在单个域上的Nginx路由器后面运行,因此我不需要SockJS提供的跨域功能.但是,由于提供此功能,SockJS根本不公开客户端的cookie数据.到目前为止,我通过cookie和查询字符串令牌对Socket.io进行了2因素授权,而这对SockJS来说是不可能的(使用Engine.io).
我已经阅读了几乎所有可用的内容和两者的优点和缺点,但似乎到目前为止没有太多讨论或发布,特别是关于Engine.io(这里只有8个问题用engine.io标记).
你喜欢哪2个图书馆中的哪一个?你在生产中使用它们吗?
哪一个可能会更积极地维持,并且在未来可能比另一个更具优势?
有没有办法将WebSockets与SockJS客户端和Spring 4服务器一起使用但不使用STOMP?
基于Spring网站的这个教程,我知道如何使用Stomp和Spring 4设置基于WebSocket的应用程序.在客户端,我们有:
var socket = new SockJS('/hello');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting){
showGreeting(JSON.parse(greeting.body).content);
});
});
Run Code Online (Sandbox Code Playgroud)
在服务器端,我们在控制器中有以下内容:
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(3000); // simulated delay
return new Greeting("Hello, " + message.getName() + "!");
}
Run Code Online (Sandbox Code Playgroud)
现在,据我所知,@MessageMapping("/hello")确保如果将消息发送到目标"/hello",则将greeting()调用该方法.并且由于stompClient订阅了"/topic/greetings",所以@SendTo("/topic/greetings")会将消息发送回stompClient.
但是上面的问题是stompClient是一个Stomp对象.我想简单地使用sock.send('test');并将其发送到我的服务器目的地.我想做@SendTo("myownclientdestinationmap"),我可以收到它
sock.onmessage = function(e) {
console.log('message', e.data);
};
Run Code Online (Sandbox Code Playgroud)
那么,使用Spring 4,SockJS和没有Stomp的任何方法都可以做到这一点?或者Spring 4 WebSocket只支持Stomp?
我Auth0用于我的用户身份验证只允许登录用户访问Spring(Boot)RestController.此时我正在创建一个实时消息功能,用户可以使用和从Angular 2客户端(localhost:4200)发送消息到Spring服务器(localhost:8081).stompjssockjs
尝试创建Stomp客户端并启动连接时,我收到以下控制台错误:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Run Code Online (Sandbox Code Playgroud)
在研究了这个问题之后,看起来无法同时设置选项origins =*和credentials = true.当我已经将WebSocketConfig中允许的原点设置为客户端域时,如何解决此问题?
Angular 2组件
connect() {
var socket = new SockJS('http://localhost:8081/chat');
this.stompClient = Stomp.over(socket);
this.stompClient.connect({}, function(result) {
console.log('Connected: ' + result); …Run Code Online (Sandbox Code Playgroud) Spring中的WebSockets是一个相当新的话题,我很累.
我的问题是连接到来自不同域的服务,我正在使用Lineman构建前端端和Spring Boot做后端端,我将这些应用程序放在两个不同的端口上:8000和8080在localhost上.
我遇到了'Access-Control-Allow-Origin'标题的问题但我通过在服务器端添加一个过滤器来解决它,该过滤器将允许的原点添加到标题中.在此之后我开始在连接上收到以下错误:
GET http://localhost:8080/socket/info 403 (Forbidden)
AbstractXHRObject._start @ sockjs-0.3.4.js:807
(anonymous function) @sockjs-0.3.4.js:841
Run Code Online (Sandbox Code Playgroud)
我在项目中没有Spring Security,因此这不是授权问题,错误指向sockJS:that.xhr.send(payload); - 从未定义有效负载.我尝试过但无法找到可能开始的呼叫根.
我想在设置连接时是否需要向SockJS和Stomp添加一些额外的信息,但是这个工具的两个wiki页面中没有太多的示例和注释.
你会发现Bellow连接JS代码.
var socket = new SockJS("http://localhost:8080/socket");
client = Stomp.over(socket);
client.connect({'login': BoatsGame.userName,
'passcode': 'guest'},
function (frame) {
....
The Server Side has a MessageBroker configured :
@Configuration
@EnableWebSocketMessageBroker
public class MessageBrokerConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
container.setMaxTextMessageBufferSize(8192);
container.setMaxBinaryMessageBufferSize(8192);
return container;
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
//config.enableStompBrokerRelay("/queue", "/topic");
config.enableSimpleBroker("/queue", "/topic","/user");
config.setApplicationDestinationPrefixes("/BoatBattleGame");
}
@Override …Run Code Online (Sandbox Code Playgroud) 我想了解convertAndSendToUser如何在Spring SockJS + Websocket框架中工作.
在客户端,我们将连接为
stompClient.connect(login, password, callback())
Run Code Online (Sandbox Code Playgroud)
这将导致连接请求与登录和密码的"Stomp凭证",例如,如果我们处理SessionConnectEvent http://www.sergialmar.com/2014/03/detect-websocket-connects-and-disconnects-in -spring-4 /
但我仍然不清楚这是否是服务器端向队列发送操作的"用户":
simpMessagingTemplate.convertAndSendToUser(username, "/queue/reply", message);
Run Code Online (Sandbox Code Playgroud)
我能得到的最接近的是阅读这个帖子向Spring Websocket上的特定用户发送消息,由Thanh Nguyen Van回答,但目前还不清楚.
基本上我需要做的是订阅一些客户端到同一主题,但在服务器上,发送不同的数据.客户可以提供用户标识符.
我正在使用带有Go的Sockjs,但是当javascript客户端将json发送到服务器时,它会将其转义,并将其作为[]字节发送.我正在试图找出如何解析json,以便我可以读取数据.但我得到这个错误.
json:无法将字符串解组为main.Msg类型的Go值
我怎样才能解决这个问题?html.UnescapeString()没有效果:/
val, err := session.ReadMessage()
if err != nil {
break
}
var msg Msg
err = json.Unmarshal(val, &msg)
fmt.Printf("%v", val)
fmt.Printf("%v", err)
type Msg struct {
Channel string
Name string
Msg string
}
//Output
"{\"channel\":\"buu\",\"name\":\"john\", \"msg\":\"doe\"}"
json: cannot unmarshal string into Go value of type main.Msg
Run Code Online (Sandbox Code Playgroud) Spring Boot应用程序中的Websocket - 获取403禁止
当我在eclipse(没有弹簧启动)中运行时,我可以使用sockjs/stompjs从客户端连接到websocket.
但是当我为websocket代码创建一个Spring启动jar(gradlew build)并运行java -jar websocket-code.jar时,我得到403错误连接到websocket.
我没有websockets的身份验证.我有一个CORS过滤器,并认为请求/响应中的所有标题正确.
下面是我的build.gradle
apply plugin: 'java'
apply plugin: 'spring-boot'
apply plugin: 'war'
sourceCompatibility = 1.7
version = '1.0'
repositories {
mavenCentral()
}
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.5.RELEASE")
}
}
configurations {
compile.exclude module: "spring-boot-starter-tomcat"
}
dependencies {
compile "org.springframework:spring-web:$spring_version"
compile "org.springframework:spring-webmvc:$spring_version"
compile "org.springframework:spring-websocket:$spring_version"
compile "org.springframework:spring-messaging:$spring_version"
compile "org.springframework.boot:spring-boot-starter-websocket"
compile "org.springframework.boot:spring-boot-starter-web"
compile "com.fasterxml.jackson.core:jackson-databind:2.6.2"
compile "com.fasterxml.jackson.core:jackson-core:2.6.2"
compile "com.fasterxml.jackson.core:jackson-annotations:2.6.2"
compile "org.springframework.amqp:spring-rabbit:1.3.5.RELEASE"
compile("org.springframework:spring-tx")
compile("org.springframework.boot:spring-boot-starter-web:1.2.6.RELEASE")
compile("org.springframework.boot:spring-boot-starter-jetty:1.2.6.RELEASE")
testCompile group: 'junit', name: 'junit', version: '4.11'
testCompile …Run Code Online (Sandbox Code Playgroud)