Websocket是HTML5新增的一种全双工通信协议,客户端和服务端基于TCP握手连接成功后,两者之间就可以建立持久性的连接,实现双向数据传输。
Socket.io不是Websocket,它只是将Websocket和轮询 (Polling)机制以及其它的实时通信方式封装成了通用的接口,并且在服务端实现了这些实时机制的相应代码。也就是说,Websocket仅仅是 Socket.io实现实时通信的一个子集。因此Websocket客户端连接不上Socket.io服务端,当然Socket.io客户端也连接不上Websocket服务端。
思路:
技术支持:CommandLineRunner
假如我们想要在Spring项目启动完成后执行一些方法或者脚本,可以使用一下方式,但明显过于粗糙,因此可以实现CommandLineRunner中的run方法。
@SpringBootApplication
public class ImApplication {
public static void main(String[] args) {
SpringApplication.run(ImApplication.class, args);
System.out.println("运行方法1");
System.out.println("运行方法2");
System.out.println("运行方法3");
System.out.println("运行方法4");
}
}
我们还可以自定义方法的执行顺序
package com.im;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@SpringBootApplication
public class ImApplication {
public static void main(String[] args) {
SpringApplication.run(ImApplication.class, args);
}
}
@Component
@Order(1)
class Function1 implements CommandLineRunner{
@Override
public void run(String... args) throws Exception {
System.out.println("运行方法1");
}
}
@Component
@Order(2)
class Function2 implements CommandLineRunner{
@Override
public void run(String... args) throws Exception {
System.out.println("运行方法2");
}
}
@Component
@Order(3)
class Function3 implements CommandLineRunner{
@Override
public void run(String... args) throws Exception {
System.out.println("运行方法3");
}
}
配置 SocketIOServer
import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
@Configuration
public class SocketConfig {
@Value("${websocket.app.appHost}")
private String appHost;
@Value("${websocket.app.appPort}")
private int appPort;
@Resource
private AppClientHandler appClientHandler;
@Bean(name = "appServer")
public SocketIOServer appIOServer() {
//创建Socket,并设置监听端口
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
// 设置主机名,默认是0.0.0.0
config.setHostname(appHost);
// 设置监听端口
config.setPort(appPort);
// 协议升级超时时间(毫秒),默认10000。HTTP握手升级为ws协议超时时间
config.setUpgradeTimeout(10000);
// Ping消息间隔(毫秒),默认25000。客户端向服务器发送一条心跳消息间隔
config.setPingInterval(25000);
// Ping消息超时时间(毫秒),默认60000,这个时间间隔内没有接收到心跳消息就会发送超时事件
config.setPingTimeout(60000);
SocketIOServer server = new SocketIOServer(config);
server.addListeners(appClientHandler, AppClientHandler.class);
return server;
}
}
抽象用户code获取方法
每个系统确认建立连接时的用户信息都有所不同,例子中通过解析token来获取当前用户code,又因为使用的Spring Security进行认证,所有看着代码较为复杂,实际生产根据各自系统获取用户唯一标识即可。
import com.corundumstudio.socketio.HandshakeData;
import com.corundumstudio.socketio.SocketIOClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Objects;
@Component
public class AbstractHandler {
private static final Logger logger = LoggerFactory.getLogger(AbstractHandler.class);
@Resource
private TokenStore tokenStore;
private static final String TOKEN_PREFIX = "Bearer";
/**
* 获取用户编号
*
* @param client 请求的客户端信息
* @return 用户账号
*/
public String getUserCode(SocketIOClient client) {
HandshakeData handshakeData = client.getHandshakeData();
//原始token,前端传过来
String token = handshakeData.getSingleUrlParam(CommonConstants.TOKEN);
if (StringUtils.isBlank(token) || (token.length() - CommonConstants.ONE) < (TOKEN_PREFIX.length() + CommonConstants.ONE)) {
logger.warn("socket请求token异常,token非法【{}】,sessionId->{}", token, client.getSessionId());
client.sendEvent("fail", 403);
return null;
}
//把token前缀去掉支掉
token = token.substring(TOKEN_PREFIX.length() + CommonConstants.ONE);
//根据token获取accessToken
OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
if (Objects.isNull(accessToken) || StringUtils.isBlank(accessToken.getValue())) {
logger.warn("socket请求token异常,token非法【{}】,根据toke找不到accessToken,sessionId->{}", token, client.getSessionId());
client.sendEvent("fail", 403);
return null;
}
//根据accessToken,获取用户登录信息
OAuth2Authentication auth2Authentication = tokenStore.readAuthentication(accessToken);
if (Objects.isNull(auth2Authentication) || StringUtils.isBlank(auth2Authentication.getName())) {
logger.warn("socket请求token异常,token非法【{}】,根据toke找不到用户账号,sessionId->{}", token, client.getSessionId());
client.sendEvent("fail", 403);
return null;
}
PigUser pigUser = (PigUser)auth2Authentication.getPrincipal();
return pigUser.getUserCode();
}
}
编写WebClientHandler容器
这个容器其实就是干四件件事。
import com.alibaba.fastjson.JSONObject;
import com.chinaentropy.systembase.websocket.AbstractHandler;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* SocketIOClient容器
*/
@Component
public class WebClientHandler extends AbstractHandler {
private static final Logger logger = LoggerFactory.getLogger(WebClientHandler.class);
private static ConcurrentHashMap<SocketIOClient, String> clientMap = new ConcurrentHashMap<>();
public ConcurrentHashMap<SocketIOClient, String> getClientMap() {
return clientMap;
}
/**
* 添加connect事件,当客户端发起连接时调用
*
* @param client 连接的客户端
*/
@OnConnect
public void onConnect(SocketIOClient client) {
logger.info("客户端发起连接, sessionId: {}", client.getSessionId());
String userCode = getUserCode(client);
if (StringUtils.isBlank(userCode)) {
logger.warn("websocket请求token异常. sessionId->{}", client.getSessionId());
client.sendEvent("fail", 403);
return;
}
clientMap.put(client, userCode);
}
/**
* 接收(监听)来着 web端浏览器发送的事件、事件触发为 webevent
*
* @return void
* @Param [client, request, data]
*/
@OnEvent("event")
public void chatEvent(SocketIOClient client, AckRequest ackRequest, String message) {
logger.info("服务端接收数据, message: {}", message);
}
/**
* 添加@OnDisconnect事件,客户端断开连接时调用,刷新客户端信息
*
* @param client 注销的客户端
*/
@OnDisconnect
public void onDisconnect(SocketIOClient client) {
logger.info("客户端断开连接, sessionId: {}", client.getSessionId().toString());
clientMap.remove(client);
client.disconnect();
}
/**
* 推送Obj给所有用户
*
* @param eventName 事件名
* @param jsonStr 参数
*/
public void pushMessage(String eventName, String jsonStr) {
clientMap.forEach((key, value) -> {
logger.info("[DispatchAppClientHandler][pushMessage]: eventName->{}, data->{}", eventName, jsonStr);
key.sendEvent(eventName, jsonStr);
});
}
/**
* 按照用户编号列表进行String消息推送
*
* @param eventName 事件名
* @param object 参数
* @param userCodeList 用户编号列表
*/
public void pushMessageByUsers(String eventName, Object object, List<String> userCodeList) {
clientMap.forEach((key, value) -> {
if (userCodeList.contains(value)) {
String data = JSONObject.toJSONString(object);
logger.info("[DispatchAppClientHandler][pushMessageByUser]: eventName->{}, data->{}, user->{}", eventName, data, value);
key.sendEvent(eventName, data);
}
});
}
Spring项目启动后,启动SocketIOServer
import com.corundumstudio.socketio.SocketIOServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class WebSocketServerRunner implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(WebSocketServerRunner.class);
@Resource
@Qualifier("appServer")
private SocketIOServer appServer;
@Override
public void run(String... args) {
logger.info("SocketIO 启动...");
appServer.start();
}
}
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
最近,当我启动我的Rails服务器时,我收到了一长串警告。虽然它不影响我的应用程序,但我想知道如何解决这些警告。我的估计是imagemagick以某种方式被调用了两次?当我在警告前后检查我的git日志时。我想知道如何解决这个问题。-bcrypt-ruby(3.1.2)-better_errors(1.0.1)+bcrypt(3.1.7)+bcrypt-ruby(3.1.5)-bcrypt(>=3.1.3)+better_errors(1.1.0)bcrypt和imagemagick有关系吗?/Users/rbchris/.rbenv/versions/2.0.0-p247/lib/ru
在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的
我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b
您如何在Rails中的实时服务器上进行有效调试,无论是在测试版/生产服务器上?我试过直接在服务器上修改文件,然后重启应用,但是修改好像没有生效,或者需要很长时间(缓存?)我也试过在本地做“脚本/服务器生产”,但是那很慢另一种选择是编码和部署,但效率很低。有人对他们如何有效地做到这一点有任何见解吗? 最佳答案 我会回答你的问题,即使我不同意这种热修补服务器代码的方式:)首先,你真的确定你已经重启了服务器吗?您可以通过跟踪日志文件来检查它。您更改的代码显示的View可能会被缓存。缓存页面位于tmp/cache文件夹下。您可以尝试手动删除
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里