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

时间:2017-07-17 10:53:18

标签: ios iphone sockets swift3

我想通过套接字在局域网中通信两个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
            }
      }
 }

0 个答案:

没有答案