美文网首页
使用websocket实现Client/Server间长时间通讯

使用websocket实现Client/Server间长时间通讯

作者: Realank | 来源:发表于2019-10-10 16:03 被阅读0次

使用场景

常规的接口调用,需要在短时间内返回,否则timeout,即使不timeout,接口调用也禁止长时间阻塞,
而通过请求+轮询结果的方式,复杂且不稳定。此时可以使用websocket

介绍

通常,我们的接口调用是客户端发起请求,服务器做应答,客户端是主动的,服务器如果想主动跟客户端通讯,就需要客户端与服务器保持长连接,
而长连接有许多细节需要处理,比如心跳、断线重连等等,websocket帮我们封装了这些细节。像普通的网络连接一样简单,就可以实现全双工通讯

使用

websocket是一项协议,Socket.IO基于websocket实现,我们下面来使用Socket.IO实现类websocket通讯
(SocketIO将WebSocket、AJAX和其它的通信方式全部封装成了统一的通信接口,也就是说,我们在使用SocketIO时,不用担心兼容问题,底层会自动选用最佳的通信方式。因此说,WebSocket是SocketIO的一个子集。
另外,如果后端采用的是原生WebSocket,不建议使用SocketIO。因为SocketIO定制了专有的协议,并不是纯粹的WebSocket,可能会遭遇适配问题。不过,SocketIO的API极其易用,纯ws可以使用SocketRocket)

服务端:

Node.js实现:

安装依赖:npm install socket.io -s
代码:

const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connection', client => {
  console.log('connection ' + client.id)
  client.on('toServer', data => {
    console.log('[server]received ' + JSON.stringify(data))
    client.emit('toClient', "how are you")
  });
  client.on('disconnect', () => {
    console.log('disconnect')
  });
});
server.listen(6000);

客户端:

JS实现:

安装依赖:npm install socket.io-client -s
代码:

client = require('socket.io-client')

var socket = client('http://localhost:6000');
socket.on('connect', function(){});
socket.on('toClient', function(data){
  console.log('[client web]received ' + JSON.stringify(data))
});
socket.on('disconnect', function(){});
setInterval(()=>{
  socket.emit('toServer', "hello im web")
},3000)



iOS实现:

Podfile添加:
pod 'Socket.IO-Client-Swift', '~> 15.1.0'

代码:

@import SocketIO;

NSURL* url = [[NSURL alloc] initWithString:@"http://10.101.228.63:6000"];
static SocketManager* manager = nil;
manager = [[SocketManager alloc] initWithSocketURL:url config:@{@"log": @NO, @"compress": @YES}];
SocketIOClient* socket = manager.defaultSocket;

[socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {

    NSLog(@"socket connected");

    [socket emit:@"toServer" with:@[@"hello im ios"]];

}];


[socket on:@"toClient" callback:^(NSArray* data, SocketAckEmitter* ack) {

    NSLog(@"[client] received %@",data);

}];

[socket connect];

相关文章

网友评论

      本文标题:使用websocket实现Client/Server间长时间通讯

      本文链接:https://www.haomeiwen.com/subject/gmlapctx.html