首页 > 解决方案 > iOS websocket连接即时断开

问题描述

我正在尝试在 iOS 客户端(iPad Air 2)和我的 C# 服务器之间建立 websocket 连接。

在 iOS 上,我使用 Starscream ( https://github.com/daltoniam/Starscream ) 进行 websocket 连接。但是在我成功连接到我的服务器后,它会自动断开连接。Sec-WebSocket-Accept 两边都是一样的。我猜测错误出在我的 C# 服务器中,但我无法弄清楚到底是什么问题。

这是我的iOS代码:

class ViewController: UIViewController {

var socket : WebSocket!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    socket = WebSocket(url: URL(string: "ws://192.168.188.35:80")!)
    socket.connect()
    socket.pongDelegate = self
    socket.advancedDelegate = self

}


deinit {
    socket.disconnect(forceTimeout: 0, closeCode: 0)
    socket.delegate = nil
}

}

extension ViewController: WebSocketAdvancedDelegate {
func websocketDidConnect(socket: WebSocket) {
    print("connect")
}

func websocketDidDisconnect(socket: WebSocket, error: Error?) {
    print("disconnect")
}

func websocketDidReceiveMessage(socket: WebSocket, text: String, response: WebSocket.WSResponse) {
    print("receivedMessage")
}

func websocketDidReceiveData(socket: WebSocket, data: Data, response: WebSocket.WSResponse) {
    print("receivedData")
}

func websocketHttpUpgrade(socket: WebSocket, request: String) {
    print("httpUpgradeRequest")
    print(request)
}

func websocketHttpUpgrade(socket: WebSocket, response: String) {
    print("httpUpgradeResponse")
    print(response)
}

}

这是我的 C# 服务器:

public TcpListener server;

    public MainWindow()
    {
        server = new TcpListener(IPAddress.Parse("192.168.188.35"), 80);

        server.Start();
        Console.WriteLine("Server has started on 127.0.0.1:80.{0}Waiting for a connection...", Environment.NewLine);

        TcpClient client = server.AcceptTcpClient();

        Console.WriteLine("A client connected.");

        NetworkStream stream = client.GetStream();


        while (client.Available < 3)
        {
            // wait for enough bytes to be available
        }

        Byte[] bytes = new Byte[client.Available];

        stream.Read(bytes, 0, bytes.Length);

        //translate bytes of request to string
        String data = Encoding.UTF8.GetString(bytes);

        if (Regex.IsMatch(data, "^GET"))
        {
            const string eol = "\r\n"; // HTTP/1.1 defines the sequence CR LF as the end-of-line marker

            Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + eol
                + "Connection: Upgrade" + eol
                + "Upgrade: websocket" + eol
                + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
                    System.Security.Cryptography.SHA1.Create().ComputeHash(
                        Encoding.UTF8.GetBytes(
                            new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
                        )
                    )
                ) + eol
                + eol);

            stream.Write(response, 0, response.Length);
        }
        else
        {

        }

    }

标签: c#iosswiftstarscream

解决方案


我发现了问题,它在我的 C# 服务器内部:在客户端连接并且握手成功后,您必须调用

server.AcceptSocket(); //or server.AcceptSocketAsync()

推荐阅读