2

I want to exchange data between iPad and an embedded device through TCP. I am using the TCP frame work CocoaAsyncSocket. Using this i created a client and server which are actually two different ipads.

I am able to connect from the client to the server by giving the servers ip address to the client and the delegate for accepting the new connection is getting called on the server.

But i am not able to write any data from client to server also i need to do it vice versa be able to write and read from server to client.

Have used the below code for writing from client to server.

//Client side
//For making a connection with server, this is succesfull
func establishSocket() {

    do {

    try socket!.connect(toHost: "192.168.xx.xxx", onPort: 5007)
    }
    catch {
        print("Could not connect to host")
    }

}
//this is to write data to the server. 
func writeString(message:String) {
    let data = message.data(using: .utf8)
    socket?.write(data!, withTimeout: -1, tag: 1)
}


//Server side
//This is called succesfully
func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: 
GCDAsyncSocket) {
    print("Did accept on socket")
    setSocketRead()
}

func setSocketRead() {
serverSocket?.readData(to: reaaddata, withTimeout: -1, tag: 1)
}

//This is not getting called
func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: 
Int) {
    let datastring = data.base64EncodedString()
    print(datastring)
}

If you know the correct flow please help me out.

Thanks

nuteron
  • 531
  • 2
  • 8
  • 26
  • 2
    i don't know nothing about CocoaAsyncSocket, but why you try to read data from serverSocket and not from newSocket ? – user3441734 May 02 '17 at 10:14

1 Answers1

0

On the server side, you should be doing the read on the new socket, not the server socket.

http://cocoadocs.org/docsets/CocoaAsyncSocket/7.0.3/Protocols/GCDAsyncSocketDelegate.html#//api/name/socket:didAcceptNewSocket:

This is the way server side connections work. You create a socket that listens on a port. Then you call accept on that socket and it blocks waiting for a connection. When a connection is made, the accept call creates a new socket to act as the server side end point of the connection and returns. Your delegate method is called at that point with the new socket.

You might find that you also need to call accept on the listening socket again to accept more connections.

JeremyP
  • 84,577
  • 15
  • 123
  • 161