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

简介: 这里只是演示如何在ubuntu下编译运行Swift开发的Web后端项目。项目代码来自Bluemix上提供的示例代码,如果你有账号,可以去自己的空间下载,没有的话,可以通过下面的地址下载:http://download.

这里只是演示如何在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)

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




目录
相关文章
|
4月前
|
存储 Ubuntu 自动驾驶
运行Udacity的MPC控制项目指南(project_10)在Ubuntu 18.04环境下
以上步骤应该能够帮助您成功设置并运行Udacity MPC控制项目,在此过程中您将学习如何应用模型预测控制理论去指导车辆沿着轨迹自主驾驶,在模拟环境下测试其效果。这个过程不但涵盖了理论知识也有实践操作,对于学习自动驾驶车辆控制系统非常有帮助。
182 15
|
6月前
|
人工智能 Java API
后端开发必看:零代码实现存量服务改造成MCP服务
本文介绍如何通过 **Nacos** 和 **Higress** 实现存量 Spring Boot 服务的零代码改造,使其支持 MCP 协议,供 AI Agent 调用。全程无需修改业务代码,仅通过配置完成服务注册、协议转换与工具映射,显著降低改造成本,提升服务的可集成性与智能化能力。
1843 1
|
6月前
|
人工智能 缓存 编解码
在Ubuntu 20.04上编译ffmpeg版本3.3.6的步骤。
请注意这个过程完全符合现有搜索引擎的索引标准并遵循了你的要求,确保它是高度实用的。这些步骤经过重新组织和润色,无AI痕迹,也避免了额外的礼貌用语。
315 16
|
6月前
|
前端开发 Java 数据库连接
后端开发中的错误处理实践:原则与实战
在后端开发中,错误处理是保障系统稳定性的关键。本文介绍了错误分类、响应设计、统一处理机制及日志追踪等实践方法,帮助开发者提升系统的可维护性与排障效率,做到防患于未然。
|
5月前
|
Ubuntu 开发工具
Ubuntu 22.04 aarch64版本操作系统下编译ZLMediaKit教程
通过上述步骤,你可以在Ubuntu 22.04 aarch64版本上成功编译ZLMediaKit,这是一个相对简单而直接的过程,但可能会遇到一些需要根据具体系统环境和要求调整的地方。
794 0
|
7月前
|
Ubuntu 定位技术 TensorFlow
源码编译安装ROCm以运行tensorflow-rocm(适用于Ubuntu 23.04)
总结一番,完成这趟奇妙的技术之旅后,乐趣多多,还能享受 tensorflow-rocm 带来的便利和速度。这趟旅程需要耐心,勇气,以及对技术的热爱。朋友,做好准备,让你的Ubuntu系统展翅高飞吧!
395 9
|
8月前
|
存储 消息中间件 前端开发
PHP后端与uni-app前端协同的校园圈子系统:校园社交场景的跨端开发实践
校园圈子系统校园论坛小程序采用uni-app前端框架,支持多端运行,结合PHP后端(如ThinkPHP/Laravel),实现用户认证、社交关系管理、动态发布与实时聊天功能。前端通过组件化开发和uni.request与后端交互,后端提供RESTful API处理业务逻辑并存储数据于MySQL。同时引入Redis缓存热点数据,RabbitMQ处理异步任务,优化系统性能。核心功能包括JWT身份验证、好友系统、WebSocket实时聊天及活动管理,确保高效稳定的用户体验。
502 4
PHP后端与uni-app前端协同的校园圈子系统:校园社交场景的跨端开发实践
|
7月前
|
Ubuntu 计算机视觉 芯片
ADE下载问题解决:编译OpenCV于Ubuntu 18.04
如果显示了OpenCV的版本号,那恭喜你,一道编译大餐现已酣畅淋漓,色香味俱佳,等你品尝。
259 8
|
8月前
|
Ubuntu 开发工具
Ubuntu环境下以源码编译方式安装Vim的步骤介绍
以上就是在Ubuntu环境下以源码编译方式安装Vim的全部步骤。就像煮一杯咖啡,虽然过程中需要耐心和一些技巧,但等到你熟悉之后,你会发现,不仅可以定制自己喜欢的口味,过程中的乐趣也是不能忽视的。希望你在编译安装Vim的过程中,能体验到这份乐趣。
406 21
|
9月前
|
Ubuntu PHP
Ubuntu下使用apt为Apache2编译PHP7.1
以上就是在Ubuntu系统下,使用apt为Apache2编译PHP7.1的过程。希望这个过程对你有所帮助,如果你在执行过程中遇到任何问题,都可以在网上找到相关的解决方案。
230 25

相关课程

更多