如何让IBM BlueSocket在GUI应用程序上运行并支持多连接

时间:2016-07-29 08:04:40

标签: swift sockets

最近,我发现了一个名为IBM BlueSocket的纯swift套接字服务器和客户端。
它适合我,它做服务器cleint通信。 它有一个非常简单的样本。但我遇到了一些问题。
1.如何在GUI应用程序的运行循环中运行它? 2.如何运行它并支持多连接?

2 个答案:

答案 0 :(得分:2)

为了它的价值,我展示了世界上最简单的聊天客户端。

import Foundation
import Socket

// Very simplified chat client for BlueSocket - no UI, it just connects to the echo server, 
// exchanges a couple of messages and then disconnects.
// You can run two instances of Xcode on your Mac, with the BlueSocketEchoServer running in one and 
// this program running in the other. It has been tested running in the iPhone simulator, i.e., 
// under iOS, without problems.
// License: Public domain.
public class BlueSocketChatClient {

   public func runClient() {

      do {
         let chatSocket = try Socket.create(family: .inet6)

         try chatSocket.connect(to: "127.0.0.1", port: 1337)

         print("Connected to: \(chatSocket.remoteHostname) on port \(chatSocket.remotePort)")

         try readFromServer(chatSocket)

         try chatSocket.write(from: "Hello to you too!")

         try readFromServer(chatSocket)

         try chatSocket.write(from: "Bye now!\n")
         try chatSocket.write(from: "QUIT")

         sleep(1)  // Be nice to the server
         chatSocket.close()
      }
      catch {
         guard let socketError = error as? Socket.Error else {
            print("Unexpected error ...")
            return
         }
         print("Error reported:\n \(socketError.description)")
      }
   }


   // This is very simple-minded. It blocks until there is input, and it then assumes that all the 
   // relevant input has been read in one go.
   func readFromServer(_ chatSocket : Socket) throws {
      var readData = Data(capacity: chatSocket.readBufferSize)
      let bytesRead = try chatSocket.read(into: &readData)
      guard bytesRead > 0 else {
         print("Zero bytes read.")
         return
      }
      guard let response = String(data: readData, encoding: .utf8) else {
         print("Error decoding response ...")
         return
      }
      print(response)
   }
}
比尔阿布特:如果你能以任何方式使用它,欢迎你使用它。

答案 1 :(得分:1)

该示例最近已更新,并说明了使用基于GCD的Dispatch API进行多线程和支持多个连接。它还应该让您了解如何在主队列上运行它(这适用于GUI或服务器应用程序)。