如何在iOS中编写套接字服务器

如何在iOS中编写套接字服务器,ios,iphone,sockets,swift3,Ios,Iphone,Sockets,Swift3,我想通过套接字在局域网中与两台iOS设备通信。 现在,我可以通过在iOS中编写客户端代码来与web套接字通信,但我想知道是否有任何方法可以通过套接字与两个iOS设备通信,因此一个iOS设备用作服务器,另一个iOS设备用作客户端 对于客户端,我使用以下代码: // MARK:- communication initilaize Methode. func initNetworkCommunication() { //Initilize network communicati

我想通过套接字在局域网中与两台iOS设备通信。 现在,我可以通过在iOS中编写客户端代码来与web套接字通信,但我想知道是否有任何方法可以通过套接字与两个iOS设备通信,因此一个iOS设备用作服务器,另一个iOS设备用作客户端

对于客户端,我使用以下代码:

// MARK:- communication initilaize Methode.
   func initNetworkCommunication() {

        //Initilize network communication.

        host = "192.168.2.15" //Server IP
        port = 8788 //Port for communication

        Stream.getStreamsToHost(withName: host!, port: port!, inputStream: &inputstream, outputStream: &outputstream)

        if ((inputstream != nil) && (outputstream != nil)) {
            // connection  not failed.
            print("Connection to \(host!):\(port!)")

            inputstream?.delegate = self
            outputstream?.delegate = self


            inputstream?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
            outputstream?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)

            inputstream?.open()
            outputstream?.open()

        }
    }
对于处理连接,实现
StreamDelegate
的委托,如下所示:

 // MARK:- StreamDelegate Methods.
 func stream(_ aStream: Stream, handle eventCode: Stream.Event) {

       switch eventCode {

            case Stream.Event.openCompleted:
                print("Connected")

                //Make connection connect.
                outputstream_Status = true

                break

            case Stream.Event.hasBytesAvailable:
                break

            case Stream.Event.hasSpaceAvailable:
                break

            case Stream.Event.endEncountered:
                print("Connection closed by the server.")

                //Make connection disconnect.
                outputstream_Status = false

                //De-Initialize the Stream.
                closeNetworkCommunication()

                break

            case Stream.Event.errorOccurred:

                print("Can not connect to the host!")

                //Make connection disconnect.
                outputstream_Status = false

                break

            default:
                break
            }
      }
 }