【问题标题】:Events with Socket.io in iOSiOS 中使用 Socket.io 的事件
【发布时间】:2015-11-24 10:55:26
【问题描述】:

我目前正在使用 Socket.io 客户端进行 swift,并且我已经能够建立与服务器的连接,但由于某种原因,我无法接收事件。我尝试通过调试运行它,它从 iOS 客户端接收事件,但它没有执行 addUser 函数。我遗漏了一些明显的东西,但我无法弄清楚它是什么。

ma​​in.js

var app = require('http').createServer()
var io = require('socket.io')(app);
app.listen(6979)

io.on('connection', function(socket){
  console.log('a user connected');
  io.emit('hi there:');
});

io.on('addUser', function(username){
      console.log('ran addUser');
      io.emit(username);
      console.log(username);
 });

斯威夫特

import UIKit
import Socket_IO_Client_Swift

class ViewController: UIViewController {
    var name:String?
    let socket = SocketIOClient(socketURL: "http://xxx.xxx.xxx.xxx:6979", options: [.Log(true), .ForcePolling(true)])

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func connect(sender: AnyObject) {
        socket.connect()
    }

    @IBAction func sendMessage(sender: AnyObject) {

    }

    @IBAction func sendUsername(sender: AnyObject) {
        let username = "yay"
        socket.emit("addUser", username)
    }
}

【问题讨论】:

    标签: ios socket.io swift2


    【解决方案1】:

    首先它(可能)应该是

    let socket = SocketIOClient(socketURL: "/", options: [.Log(true), .ForcePolling(true)])
    

    那么服务器端应该是这样的

    io.on('connection', function(socket){
        console.log('a user connected');
    
        socket.on('addUser', function(username){
            console.log('ran addUser');
            io.emit(username); // do you really need to do it?
            console.log(username);
        });
    
    });
    

    至少这应该使您能够在服务器端接收addUser 事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-17
      • 2021-07-23
      • 1970-01-01
      • 2017-04-29
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      相关资源
      最近更新 更多