Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive data from server through socket in iOS?

I have an application in which i have to send data to server using socket connection and read data which will send by server. I am using AsyncSocket class for write and read data. I got success to write data on server and server can see the data which was send by application. Now, problem is that whenever server send some data to application then how can i receive those data using AsyncSocket class. Below is my code. I put delegates method for reading data but it never called.

var socket = AsyncSocket()

socket = AsyncSocket(delegate: self)
self.socketConnect()

func socketConnect() {
        do {
            try socket?.connectToHost("IP Address", onPort: 6968)
        } catch _ as NSError {

        }
    }



//MARK: - AsyncSocket Delegates method

    func onSocket(sock: AsyncSocket!, didConnectToHost host: String!, port: UInt16) {
        print("Connected to host : \(host) with Port : \(port)")


        let alert:UIAlertController = UIAlertController(title: "Connected", message: "Host:\(host) ** Port:\(port)", preferredStyle:.Alert)
        self.presentViewController(alert, animated: true, completion: nil)
        let action:UIAlertAction = UIAlertAction(title: "Ok", style: .Default) { (UIAlertAction) -> Void in
            print("Ok Pressed")
        }
        alert .addAction(action)

        let dict = ["iUserId":"100","iRideId":"276","type":"client"] // For client side
        var jsonString = NSString()
        do {
            let data = try NSJSONSerialization.dataWithJSONObject(dict , options: NSJSONWritingOptions.PrettyPrinted)
            jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)!

        }catch let error as NSError {
            print(error)
        }
        let reqData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
        socket.writeData(reqData, withTimeout: 1.0, tag: 100)

    }

    func onSocket(sock: AsyncSocket!, didReadPartialDataOfLength partialLength: UInt, tag: Int) {
        print("Read partial data")
    }

    func onSocket(sock: AsyncSocket!, didWriteDataWithTag tag: Int) {
        print("Data write successfully")
    }

    func onSocket(sock: AsyncSocket!, didReadData data: NSData!, withTag tag: Int) {
        print("Data read successfully")
    }

    func onSocket(sock: AsyncSocket!, willDisconnectWithError err: NSError!) {
        print("Socket disconnect with error :\(err.description)")
    }

    func onSocket(sock: AsyncSocket!, didAcceptNewSocket newSocket:  AsyncSocket!) {
       print("Accept new socket")
    }
like image 938
Birju Avatar asked Nov 09 '22 13:11

Birju


1 Answers

I have found answer for my self. What i have missed is that i have to put readdata line when socket is connected to host. So after write this didReadData method will be called and in that method also have to write a single line code that i wrote in didConnectToHost method.

func socket(sock: GCDAsyncSocket!, didConnectToHost host: String!, port: UInt16) {
        print("Connected to host : \(host) with Port : \(port)")
        socket.readDataWithTimeout(-1, tag: 0)
    }

func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) {
        print("Data read successfully")


        socket.readDataWithTimeout(-1, tag: 0)
}
like image 200
Birju Avatar answered Nov 14 '22 21:11

Birju