我正在尝试连接我的实时服务器以进行 Web 套接字连接。但是我在 iOs 中遇到了错误。
websocket已断开连接:可选(错误域=NSPOSIXErrorDomain Code=61“连接被拒绝”UserInfo={_kCFStreamErrorCodeKey=61,_kCFStreamErrorDomainKey=1})
我已经尝试过使用其他服务器,但它可以使用它。只是没有在我的代码中使用指定的服务器。两台服务器都有 https。
这是我的 iOS 源代码链接: https ://www.dropbox.com/s/v348vxxjf74dsds/websocket.zip?dl=0
import UIKit
import Starscream
class ViewController: UIViewController, WebSocketDelegate {
@IBOutlet var button: UIButton!
@IBOutlet var textfiled: UITextField!
var socket = WebSocket(url: URL(string: "https://103.240.79.191:8080")!)
override func viewDidLoad() {
super.viewDidLoad()
socket.delegate = self
debugPrint("Called")
socket.connect()
}
func websocketDidConnect(socket: WebSocketClient) {
print("websocket is connected")
socket.write(string: "connected")
}
func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
print("got some text: \(text)")
}
func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
print("websocket is disconnected: \(error)")
}
func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
debugPrint("Data")
debugPrint(data)
}
@objc func update() {
debugPrint("Called")
socket.connect()
}
@IBAction func btnclick() {
socket.write(string: textfiled.text ?? "")
}
}
请找到以下服务器端代码:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 }, () => {
console.log("Signaling server is now listening on port 8080")
});
// Broadcast to all.
wss.broadcast = (ws, data) => {
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
};
wss.on('connection', (ws) => {
console.log(`Client connected. Total connected clients: ${wss.clients.size}`)
ws.onmessage = (message) => {
console.log(message.data + "\n");
wss.broadcast(ws, message.data);
}
ws.onclose = () => {
console.log(`Client disconnected. Total connected clients: ${wss.clients.size}`)
}
});