gpt4 book ai didi

node.js - NodeJS 服务器未从 Swift 客户端接收 Socket.emit()

转载 作者:行者123 更新时间:2023-11-28 08:20:56 24 4
gpt4 key购买 nike

我正在尝试使用 NodeJS 后端快速构建一个非常简单的多人井字游戏。然而,当我尝试从我的 swift 客户端执行 socket.emit() 时,服务器无法识别它。

客户代码:

套接字管理器:

import UIKit

class SocketIOManager: NSObject {
static let sharedInstance = SocketIOManager()

override init() {
super.init()
}

var socket: SocketIOClient = SocketIOClient(socketURL: NSURL(string: "http://10.0.1.30:2000")! as URL)

func connectToServer(completionHandler: @escaping (_ userList: [[String: AnyObject]]?) -> Void) {
socket.emit("connectUser")

socket.on("userList") { ( dataArray, ack) -> Void in
completionHandler(_: dataArray[0] as? [[String: AnyObject]])
}
}

func establishConnection() {
socket.connect()
}

func closeConnection() {
socket.disconnect()
}
}

游戏场景:

import SpriteKit

class GameScene: SKScene {

let screenSize = UIScreen.main.bounds
var board = SKSpriteNode(imageNamed: "Board.png")

var users = [[String: AnyObject]]()

override func didMove(to view: SKView) {
SocketIOManager.sharedInstance.connectToServer(completionHandler: { (userList) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
if userList != nil {
self.users = userList!
}
})
})

board.size = CGSize(width: screenSize.width * 2/3, height: screenSize.width * 2/3)
board.position = CGPoint(x: screenSize.width/2, y: screenSize.height/2)

self.backgroundColor = UIColor.white
self.addChild(board)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

}

override func update(_ currentTime: TimeInterval) {

}
}

服务器代码:

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

var userList = [];

app.get('/', function(req, res){
res.send('<h1>Tic-Tac-Toe Server</h1>');
});

http.listen(2000, function(){
console.log('Listening on *:2000');
});

io.on('connection', function(clientSocket) {
console.log('a user connected');

clientSocket.on('disconnect', function() {
console.log('user disconnected');
});

clientSocket.on('connectUser', function() {
console.log('User with id ' + clientSocket.id + ' connected');

var userInfo = {};
var foundUser = false;

for (var i = 0; i < userList.length; i++) {
if (userList[i]["id"] == clientSocket.id) {
userInfo = userList[i];
foundUser = true;
break;
}
}

if (!foundUser) {
userInfo["id"] = clientSocket.id;
userList.push(userInfo);
}

io.emit("userList", userList);
io.emit("userConnectUpdate", userInfo);
});

});

特别是不起作用的消息是“connectUser”消息,但我尝试创建其他消息来测试它,但没有一个起作用。看起来好像服务器从未收到过它们。

最佳答案

由于您没有使用 https ( http://10.0.1.30:2000 ),您可能忘记在 Info.plist 中将 Allow Arbitrary Loads 设置为 YES文件在您的 iOS 项目中:

enter image description here

无论如何,我已经构建了一个有效的基本示例:

服务器端:

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

var port = 5000;

io.on('connection', function(socket) {
socket.on('message', function(data) {
console.log('client sent a message: ' + data);
});
});

http.listen(port, function() {
console.log('server up and running at %s port', port);
});

客户端:

import UIKit
import SocketIO

class ViewController: UIViewController {

let socket = SocketIOClient(socketURL: URL(string: "http://localhost:5000")!)

override func viewDidLoad() {
super.viewDidLoad()

socket.on("connect") { data, ack in
print("socket connected")

self.socket.emit("message", "Hello dear server from iOS.")
}

socket.connect()
}

}

来自服务器的日志

enter image description here

关于node.js - NodeJS 服务器未从 Swift 客户端接收 Socket.emit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com