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 = String(bytes: d, encoding: .utf8) {
print("STR\n\(str)\n")
// If I'm not wrong Here I should get the response
}
}
case .failure(let erro):
print(erro)
}
}
My problem is I am getting all request headers and after filtering I am also getting which filename
and content-type
the request header requires but I don't know how to send those file after receiving and reading the request header in reponse ..
As you can see in the above screenshot
In console area , you can see I'm getting a request of styles.afcc5f0641cf44266b1b.css
file...I just don't know how to send that file to the browser when it requests(I have full path of the file)
Thank You
index.html
so when I'm sendingindex.html
switch loop instartconnection()
is running 5 times but I am not understanding how to send the related file after reading the response I'm getting in switch loop instartconnection
....can you please explain the concept and all, I'm not getting any brief tutorials on this..... – Sonde