Swift: Create TCP listener

526 Views Asked by At

I'm new in iOS development, I work in app that send and receive msg by tcp by protocol using GCDAsyncSocket, it worked correctly in send and get response from server when I send a msg to server, but How can I make it listen to server when the server send a message to clients with out they are send any think to it, or how can I make client device as a server to accept msg from original server. If there are any other solution to change my project from GCDAsyncSocket to it, is also welcomed. Thanks in advance.

1

There are 1 best solutions below

1
RrrangeTop On

This lib give mechanism to listen server (GCDAsyncSocketDelegate).

1) your class should conform protocol - Add it to your delegate methods

2) add method func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int)

In method from step 3 will receive messages from server

Code

class MyClass: GCDAsyncSocketDelegate {

  var socket: GCDAsyncSocket?

  init() {
    self.socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue(label: "test"))
  }

  func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
    print("Data from server")
    // even if you did not made a request
  }

}