Thursday, 23 January 2020

How to get response from browser with Socket ? (I'm using SwiftSocket)

I am new to this networking in iOS so doesn't know all the concepts so well and I'm making an app which allows to show data on browser which is on device, For that I'm creating a socket-port and using SwiftSocket library

override func viewDidLoad() {
    super.viewDidLoad()
    let ip = String(getAddress(for: .wifi)!)
    self.host = ip
    print("Getting IP address of wifi\n\(self.host)\n")
    self.selfserver()
}

I think following function selfserver() initialises the server and wait for the client to connect

func selfserver()
{
    let server = TCPServer(address: self.host, port: Int32(port))
    switch server.listen() {
    case .success:
        while true {
            if let client2 = server.accept() {
                print("CLIENT ACCEPTED ....")
                 self.startconnection(senderclient: client2)
            } else {
                print("accept error")
            }
        }
    case .failure(let error):
        print(error)
    }
}

When client will try to connect following function senderclient(senderclient: TCPClient) will be called and in the response I'm sending index.html file which is saved in htmlfileURL key in Userdefaults

func startconnection(senderclient: TCPClient) {
    print("CLIENT ADD\n\(senderclient.address)\n")
    let filePath = UserDefaults.standard.url(forKey: "htmlfileURL")
    // Converting `index.html` in bytes to send
    var bytes = [UInt8]()
    if let data = NSData(contentsOfFile: filePath!.path) {
        var buffer = [UInt8](repeating: 0, count: data.length)
        data.getBytes(&buffer, length: data.length)
        bytes = buffer
        }

    senderclient.send(string: "HTTP/1.1 200 OK\n" +
        "Content-Length: \(bytes.count)\n" +
        "Connection: close\n" +
        "Content-Type: text/html\n" +
        "\n")
    switch senderclient.send(data: bytes) {
    case .success:
        let data = senderclient.read(1024*10)
        if let d = data {
            if let str = NSString(bytes: d, length: d.count, encoding: String.Encoding.utf8.rawValue) as String? {
                print("STR\n\(d)\n")
                // If I'm not wrong Here I should get the response 
            }
        }

    case .failure(let erro):
        print(erro)
    }
}

My problem is I've attached some other '.js' files with it so browser should send response for that files when I send index.html , but I am not getting any response ; Instead when I saw the page source in browser it keeps writing data of index.html in every '.js` files like you can see in following screenshot

enter image description here

Thank You in Advance...!!!!



from How to get response from browser with Socket ? (I'm using SwiftSocket)

No comments:

Post a Comment