当前位置: 移动技术网 > IT编程>开发语言>JavaScript > iOS + node.js使用Socket.IO框架进行实时通信示例

iOS + node.js使用Socket.IO框架进行实时通信示例

2018年05月21日  | 移动技术网IT编程  | 我要评论
socket.io是一个基于websocket的实时通信库,在主流平台都有很好的支持,此文主要是通过一个小例子来演示socket.io的使用。 基础环境搭建 新建一

socket.io是一个基于websocket的实时通信库,在主流平台都有很好的支持,此文主要是通过一个小例子来演示socket.io的使用。

基础环境搭建

新建一个文件夹(js工程),创建一个package.json,复制以下内容并保存。

{
 "name": "socket-chat-example",
 "version": "0.0.1",
 "description": "my first socket.io app",
 "dependencies": {}
}

然后执行npm命令,安装我们需要的依赖(express和socket.io), 请确保你电脑已经有node环境

在项目根目录也就是package.json所在的目录在终端执行以下命令

npm install --save express@4.10.2

npm install --save socket.io

进度条读完后会多这么一个文件夹,此时express和socket.io就已经安装好了,这和ios的cocopods差不多,以模块化进行加载。


然后新建一个index.js作为服务端,再建一个作为客户端。(为了方便演示,我这里有两个客户端,一个是ios端,一个是浏览器端)

这也是官方demo的演示界面,ui上没做修改


代码如下

<!doctype html>
<html>
 <head>
  <title>socket.io chat</title>
  <style>
   * { margin: 0; padding: 0; box-sizing: border-box; }
   body { font: 13px helvetica, arial; }
   form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
   form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
   form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
   #messages { list-style-type: none; margin: 0; padding: 0; }
   #messages li { padding: 5px 10px; }
   #messages li:nth-child(odd) { background: #eee; }
  </style>
 </head>
 <body>
  <ul id="messages"></ul>
  <form action="">
   <input id="m" autocomplete="off" /><button>send</button>
  </form>
 </body>
</html>

index.js

var app = require('express')();
var http = require('http').server(app);
var io  = require('socket.io')(http);

app.get('/',function(req,res){
  res.sendfile(__dirname + '/');
});
http.listen(3000,function () {
  console.log('listien 3000');
});

开启了一个server,监听3000端口,然后回到项目根目录,在终端输入node index.js

如果出现listen 3000则表明服务开启成功了,此时在浏览器访问http://localhost:3000 就能看到页面了

ios客户端的集成

新建一个ios工程,在终端cd到项目根目录创建一个podfile文件

vim podfile

复制以下内容

use_frameworks!

target 'socketio_chat_example' do #项目名
  pod 'socket.io-client-swift', '~> 8.2.0'
end

保存退出,执行命令安装依赖

pod install or pod install --verbose --no-repo-update

请确保已经有cocopods环境

ios端的ui


使用socket.io

此时我们的客户端和服务端都已经有了socket.io的环境了,接下来就是使用它进行聊天了。

socket.io中事件的处理主要通过这两个方法来实现的

on(_ event: string, callback: normalcallback)

emit(_ event: string, _ items: anyobject...)

on方法为接收事件的方法,emit为发送事件的方法

我们的需求是让浏览器和ios客户端进行单聊

服务端的处理

要想发送到指定的客户端,需要知道当前客户端的id(socket.io的id,例:3t60barlk47a2fa-aaad),但是客户端并不清楚,客户端只知道我们自己定义的id,所以我们要将socket.io的id和我们自己定义的id绑定并存储起来。

var socketarray = new array();

io.on('connection', function(socket){
  var islogin = false;
  console.log('**********新加入了一个用户*********',socket.id);
  socket.on('login',function (userid) {
    if(islogin) return;
    socket.userid = userid;
    socketarray.push(socket);
    islogin = true;

  });
  socket.on('privatemessage',function (data) {
    console.log(data);
  })
  socket.on('chat message', function(data){
    var to  = data.touser;
    var message = data.message;
    for(var i = 0;i<socketarray.length;i++){
      var receivedata = socketarray[i];
      if (receivedata.userid == to){
        io.to([receivedata.socketid]).emit('privatemessage',''+receivedata.userid+':'+message);
      }
    }
  });
  socket.on('disconnect',function () {
    console.log('***********用户退出登陆************,'+socket.id);
  })
});

客户端的处理

浏览器的处理

<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  var socket = io();
  socket.emit('login','30621');
  $('form').submit(function(){
    socket.emit('chat message',{'touser':'30342','message':$('#m').val()} );
    $('#m').val('');
    return false;
  });
  socket.on('chat message', function(msg){
    $('#messages').append($('<li>').text(msg));
  });
  socket.on('privatemessage',function (msg) {
    $('#messages').append($('<li>').text(msg));
  });
</script>

ios端的处理

ios在初始化的时候需要一个config字典,config可以配置诸如log日志输出等设置

- (socketioclient *)client{
  if (!_client) {
    nsurl* url = [[nsurl alloc] initwithstring:@"http://localhost:3000"];
    _client = [[socketioclient alloc] initwithsocketurl:url config:@{@"log": @yes, @"forcepolling": @yes}];

  }
  return _client;
}

- (void)connection{

  [self.client on:@"connect" callback:^(nsarray* data, socketackemitter* ack) {
    nslog(@"*************\n\nios客户端上线\n\n*************");
    [self.client emit:@"login" with:@[@"30342"]];
  }];
  [self.client on:@"chat message" callback:^(nsarray * _nonnull event, socketackemitter * _nonnull ack) {
    if (event[0] && ![event[0] isequaltostring:@""]) {
      [self.messagearray insertobject:event[0] atindex:0];
      [self.messagetableview insertrowsatindexpaths:@[[nsindexpath indexpathforrow:0 insection:0]] withrowanimation:uitableviewrowanimationtop];
    }
  }];
  [self.client on:@"privatemessage" callback:^(nsarray * _nonnull event, socketackemitter * _nonnull ack) {
    if (event[0] && ![event[0] isequaltostring:@""]) {
      [self.messagearray insertobject:event[0] atindex:0];
      [self.messagetableview insertrowsatindexpaths:@[[nsindexpath indexpathforrow:0 insection:0]] withrowanimation:uitableviewrowanimationtop];
    }
  }];
  [self.client on:@"disconnect" callback:^(nsarray * _nonnull event, socketackemitter * _nonnull ack) {
    nslog(@"*************\n\nios客户端下线\n\n*************%@",event?event[0]:@"");
  }];
  [self.client on:@"error" callback:^(nsarray * _nonnull event, socketackemitter * _nonnull ack) {
    nslog(@"*************\n\n%@\n\n*************",event?event[0]:@"");
  }];
  [self.client connect];

}
//按钮点击事件
- (ibaction)sendmessage:(id)sender {
  if (self.inputview.text.length>0) {

    [self.client emit:@"chat message" with:@[@{@"touser":@"30621",@"message":self.inputview.text}]];
    [self.messagearray insertobject:self.inputview.text atindex:0];
    [self.messagetableview insertrowsatindexpaths:@[[nsindexpath indexpathforrow:0 insection:0]] withrowanimation:uitableviewrowanimationtop];
    self.inputview.text = @"";
  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网