Writing an Ice Application with Swift

This page shows how to create an Ice application with Swift using the Ice Swift mapping.

On this page:

Compiling a Slice Definition for Swift

The first step in creating our C++ application is to compile our Slice definition to generate Swift proxies and skeletons. You can compile the definition as follows:

slice2swift Printer.ice

The slice2swift compiler produces a single Swift source file from this definition, Printer.swift. This file must be incorporated into both the client and the server.

Writing and Compiling a Server in Swift

The source code for the server takes only a few lines and is shown in full here:

Swift
import Foundation
import Ice

class PrinterI: Printer {
    func printString(s: String, current _: Ice.Current) {
        print(s)
    }
}

func run() -> Int32 {
    do {
        let communicator = try Ice.initialize(CommandLine.arguments)
        defer {
            communicator.destroy()
        }

        let adapter = try communicator.createObjectAdapterWithEndpoints(name: "SimplePrinterAdapter",
                                                                        endpoints: "default -h localhost -p 10000")
        let servant = PrinterI()
        try adapter.add(servant: PrinterDisp(servant), id: Ice.stringToIdentity("SimplePrinter"))
        try adapter.activate()

        communicator.waitForShutdown()
        return 0
    } catch {
        print("Error: \(error)\n")
        return 1
    }
}

exit(run())

Every Ice source file starts with an import directive for Ice, which contains the definitions for the Ice run time. We also import Foundation for the exit call at the end of the program. Our server implements a single printer servant, of type PrinterI. Looking at the generated code in Printer.swift, we find the following:

Swift
public protocol Printer {
    func printString(s: Swift.String, current: Ice.Current) throws
}

The Printer skeleton protocol is generated by the Slice compiler. Our servant class (or struct) adopts the skeleton protocol to provide an implementation of the printString method. (By convention, we use an I-suffix to indicate that the servant class or struct implements a Slice interface.)

Swift
struct PrinterI: Printer {
    func printString(s: String, current _: Ice.Current) {
        print(s)
    }
}

The implementation of the printString method is trivial: it simply prints its string argument.

Note that printString has a second parameter of type Ice.Current. We will examine the purpose of the Ice.Current parameter later.

What follows is the server main program. Note the general structure of the code:

Swift
func run() -> Int32 {
    do {
        let communicator = try Ice.initialize(CommandLine.arguments)
        defer {
            communicator.destroy()
        }

        ...

        return 0
    } catch {
        print("Error: \(error)\n")
        return 1
    }
}

exit(run())

The body of run contains a do/catch block, and we start by creating a Communicator with Ice.initialize. We pass CommandLine.arguments to Ice.initialize because the server may have command-line arguments that are of interest to the run time; for this example, the server does not require any command-line arguments.

Next, we have the actual server code:

Swift
        let adapter = try communicator.createObjectAdapterWithEndpoints(name: "SimplePrinterAdapter",
                                                                        endpoints: "default -h localhost -p 10000")
        let servant = PrinterI()
        try adapter.add(servant: PrinterDisp(servant), id: Ice.stringToIdentity("SimplePrinter"))
        try adapter.activate()        
        communicator.waitForShutdown()

The code goes through the following steps:

  1. We create an object adapter by calling createObjectAdapterWithEndpoints on the Communicator instance. The arguments we pass are "SimplePrinterAdapter" (which is the name of the adapter) and "default -p 10000", which instructs the adapter to listen for incoming requests using the default protocol (TCP/IP) at port number 10000.
  2. At this point, the server-side run time is initialized and we create a servant for our Printer interface by instantiating a PrinterI object.
  3. We inform the object adapter of the presence of a new servant by calling add on the adapter; the arguments to add are an instance of a dispatcher struct (PrinterDisp) that holds the servant we have just instantiated, plus an identifier. In this case, the string "SimplePrinter" is the name of the Ice object. (If we had multiple printers, each would have a different name or, more correctly, a different object identity.)
  4. Next, we activate the adapter by calling its activate method. (The adapter is initially created in a holding state; this is useful if we have many servants that share the same adapter and do not want requests to be processed until after all the servants have been instantiated.) The server starts to process incoming requests from clients as soon as the adapter is activated.
  5. Finally, we call waitForShutdown. This call suspends the calling thread until the shutdown of the server completes. (For now, we will simply interrupt the server on the command line when we no longer need it, which kills the server immediately)

We then build this server code (main.swift) together with the generated Printer.swift to create the server application, server.

Writing and Compiling a Client in Swift

The client code looks very similar to the server. Here it is in full:

Swift
import Foundation
import Ice

func run() -> Int32 {
    do {
        let communicator = try Ice.initialize(CommandLine.arguments)
        defer {
            communicator.destroy()
        }

        guard let obj = try communicator.stringToProxy("SimplePrinter:default -h localhost -p 10000"),
              let printer = try checkedCast(prx: obj, type: PrinterPrx.self) else {
            print("Invalid proxy")
            return 1
        }

        try printer.printString("Hello World!")
        return 0
    } catch {
        print("Error: \(error)")
        return 1
    }
}

exit(run())

Note that the overall code layout is the same as for the server: we import Ice and Foundation, and we use the same do/catch block to deal with errors.

The client code does the following:

  1. As for the server, we initialize the Ice run time by creating a Communicator object.
  2. The next step is to obtain a proxy for the remote printer. We create a proxy by calling stringToProxy on the communicator, with the string "SimplePrinter:default -p 10000". Note that the string contains the object identity and the port number that was used by the server. (Obviously, hard-coding object identities and port numbers into our applications is a bad idea, but it will do for now; we will see more architecturally sound ways of doing this when we discuss IceGrid.)
  3. The proxy returned by stringToProxy is of type Ice.ObjectPrx, which is at the root of the inheritance tree for interfaces. But to actually talk to our printer, we need a proxy for a Printer interface, not an Object interface. To do this, we need to do a down-cast by calling checkedCast. A checked cast sends a message to the server, effectively asking "is this a proxy for a Printer interface?" If so, the call returns a proxy to a Printer; otherwise, if the proxy denotes an interface of some other type, the call returns a null proxy.
  4. We now have a live proxy in our address space and can call the printString method, passing it the time-honored "Hello World!" string. The server prints that string on its terminal.

Finally, we build this client code (main.swift) together with the generated Printer.swift to create the client application, client.

Running Client and Server in Swift

To run client and server, we first start the server in a separate window:

./server

At this point, we won't see anything because the server simply waits for a client to connect to it. We run the client in a different window:

./client

The client runs and exits without producing any output; however, in the server window, we see the "Hello World!" that is produced by the printer. To get rid of the server, we interrupt it on the command line for now.

If anything goes wrong, the client will print an error message. For example, if we run the client without having first started the server, we get:

Error: ice-demos/swift/Carthage/Checkouts/ice/cpp/src/Ice/Network.cpp: 2713: ::Ice::ConnectionRefusedException:
connection refused: Connection refused

This error also shows that Ice for Swift uses Ice for C++ under the hood.


See Also