我正试图用一个NodeJS后端快速组合一个非常简单的多人tic-tac-toe游戏。但是,当我尝试从我的swift客户端执行socket.emit()时,服务器无法识别它。
客户代码:
SocketIOManager:
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”,但我试图创建其他人来测试它,但没有一个能够正常工作。看起来好像服务器从未接收过它们。
答案 0 :(得分:0)
由于您未使用https(http://10.0.1.30:2000),可能您忘记在Info.plist
文件中将允许任意载入设置为是在您的iOS项目中:
无论如何,我已经建立了一个基本的例子:
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()
}
}