IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]《Swift入门》ubuntu下编译运行Swift开发的Web后端示例

    testcs_dn发表于 2016-05-08 12:56:18
    love 0

    这里只是演示如何在ubuntu下编译运行Swift开发的Web后端项目。

    项目代码来自Bluemix上提供的示例代码,如果你有账号,可以去自己的空间下载,没有的话,可以通过下面的地址下载:

    http://download.csdn.net/detail/testcs_dn/9513395


    编译环境安装配置请参考:Ubuntu 14 server安装Swift运行环境

    环境配置好之后,将下载的示例代码解压出来:


    主要代码是“main.swift”,内容如下:

    /**
     * Copyright IBM Corporation 2016
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     **/
    
    /**
    * Creates a simple HTTP server that listens for incoming connections on port 9080.
    * For each request receieved, the server simply sends a simple hello world message
    * back to the client.
    **/
    
    #if os(Linux)
    import Glibc
    #else
    import Darwin
    #endif
    import Utils
    import Foundation
    
    // Create server socket
    let address = parseAddress()
    let server_sockfd = createSocket(address)
    // Listen on socket with queue of 5
    listen(server_sockfd, 5)
    var active_fd_set = fd_set()
    print("Server is listening on port: \(address.port)\n")
    
    // Initialize the set of active sockets
    fdSet(server_sockfd, set: &active_fd_set)
    
    let FD_SETSIZE = Int32(1024)
    
    // Generate HTTP response
    // Get environment variables
    let environmentVars = NSProcessInfo.processInfo().environment
    var responseBody = "<html><body>Hello from Swift on Linux!" +
      "<br />" +
      "<br />" +
      "<table border=\"1\">" +
      "<tr><th>Env Variable</th><th>Value</th></tr>"
    
    for (variable, value) in environmentVars {
        responseBody += "<tr><td>\(variable)</td><td>\(value)</td></tr>\n"
    }
    
    responseBody += "</table></body></html>"
    
    let httpResponse = "HTTP/1.0 200 OK\n" +
      "Content-Type: text/html\n" +
      "Content-Length: \(responseBody.length) \n\n" +
      responseBody
    
    var clientname = sockaddr_in()
    while true {
      // Block until input arrives on one or more active sockets
      var read_fd_set = active_fd_set;
      select(FD_SETSIZE, &read_fd_set, nil, nil, nil)
      // Service all the sockets with input pending
      for i in 0..<FD_SETSIZE {
        if fdIsSet(i,set: &read_fd_set) {
          if i == server_sockfd {
            // Connection request on original socket
            var size = sizeof(sockaddr_in)
            // Accept request and assign socket
            withUnsafeMutablePointers(&clientname, &size) { up1, up2 in
              var client_sockfd = accept(server_sockfd,
                UnsafeMutablePointer(up1),
                UnsafeMutablePointer(up2))
                print("Received connection request from client: " + String(inet_ntoa (clientname.sin_addr)) + ", port " + String(UInt16(clientname.sin_port).bigEndian))
                fdSet(client_sockfd, set: &active_fd_set)
            }
          }
          else {
            // Send HTTP response back to client
            write(i, httpResponse, httpResponse.characters.count)
            // Close client socket
            close(i)
            fdClr(i, set: &active_fd_set)
          }
        }
      }
    }
    
    可通过以下命令编译并启动服务:

    root@ubuntu:/home/aven/swifttrans# swift build
    root@ubuntu:/home/aven/swifttrans# .build/debug/Server
    Server is listening on port: 9080

    编译时,可能会出现以下错误:

    error: unable to invoke subcommand: /usr/bin/swift-build (No such file or directory)

    服务启动成功后,我们就可以通过浏览器访问了,结果如下图:






沪ICP备19023445号-2号
友情链接