直播项目笔记(三)

2017-11-30  本文已影响0人  Closer3

IM编程

整合工具栏

let sendBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 32))
sendBtn.setTitleColor(UIColor.black, for: .normal)
sendBtn.setTitle("删除", for: .normal)
inputTextField.rightView = sendBtn
// 如果不加这个属性按钮不会显示
inputTextField.rightViewMode = .always
// 定义一个闭包
var textCallback: ((String) -> Void)?

// 给闭包复制
textCallback("hello world")

// 调用闭包
// weak self 防止循环引用
textCallback = { [weak self] text in 
    print(text) // "hello world"
}
// MARK: 注册通知
override func viewDidLoad() {
  super.viewDidLoad()
  
  setupUI()
  NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}

// 注销通知
deinit {
   NotificationCenter.default.removeObserver(self)
}

// 处理方法
@objc fileprivate func keyboardWillChangeFrame(_ note : Notification) {
   let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
   let endFrame = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
   let inputViewY = endFrame.origin.y - kChatToolsViewHeight
   
   UIView.animate(withDuration: duration, animations: {
       UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: 7)!)
       let endY = inputViewY == (kScreenH - kChatToolsViewHeight) ? kScreenH : inputViewY
       self.chatToolsView.frame.origin.y = endY
   })
}

// 发送通知
inputTextField.becomeFirstResponder()

IM编程

Socket 在实际项目中的应用

大多应用在实时通讯

TCP/UDP

iOS中Socket编程

消息传输

TCP在传输数据时,传输的是字节流

在读取消息时,需要知道数据的长度, 否则就会出现读取不完整或者读取长度过多的情况, 因此读取方法要求我们传入本次读取的消息长度

如何解决该问题呢?

消息类型 ProtocolBuffer

ysocket 的使用(以TCP为例)

fileprivate lazy var serverSocket: TCPServer = TCPServer(address: "0.0.0.0", port: 7878)
fileprivate var isServerRunning : Bool = false

func startRunning() {
   // 1.开始监听
   serverSocket.listen()
   isServerRunning = true
   
   // 2.开启接受客户端 异步 否则阻塞主线程
   DispatchQueue.global().async {
       while self.isServerRunning {
           if let client = self.serverSocket.accept() {
               if let lMsg = client.read(4) {
                   // 1.读取长度的data
                   let headData = Data(bytes: lMsg, count: 4)
                   var length: Int = 0
                   (headData as NSData).getBytes(&length, length: 4)
                   
                   // 2.根据长度, 读取真实消息
                   guard let msg = client.read(length) else {
                       return
                   }
                   let data = Data(bytes: msg, count: length)
                   let str = String.init(data: data, encoding: String.Encoding.utf8)!
                   print(str)
               } else {
                   // isClientConnected = false
                   print("客户端断开了连接")
                   client.close()
               }
           }
       }
   }
   
}
    
func stopRunning() {
   isServerRunning = false
}
fileprivate lazy var clientSocket: TCPClient = TCPClient(address: "0.0.0.0", port: 7878)

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
   switch clientSocket.connect(timeout: 5) {
   case .success:
       let str = "Hello World"
       let data = str.data(using: String.Encoding.utf8)!
       // 1.将消息长度, 写入到data
       var length = data.count
       let headerData = Data(bytes: &length, count: 4)
       // 2.发送消息
       let totalData = headerData + data
       switch clientSocket.send(data: totalData) {
       case .success:
           print("发送成功")
       case .failure(let error):
           print(error)
       }
   case .failure(let error):
       print(error)
   }
}

ProtocolBuffer使用

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install automake
brew install libtool
brew install protobuf
brew install protobuf-swift
use_frameworks!
pod 'ProtocolBuffers-Swift'
因为服务器使用Mac编写,不能直接使用cocoapods集成
因为需要将工程编译为静态库来集成
    到Git中下载整个库
    执行脚本: ./scripts/build.sh
    添加: ./src/ProtocolBuffers/  ProtocolBuffers.xcodeproj到项目中

ProtocolBuffer的使用

在项目中, 创建一个(或多个).proto文件
之后会通过该文件, 自动帮我们生成需要的源文件(比如C++生成.cpp源文件, 比如java生成.java源文件, Swift就生成.swift源文件)
syntax = "proto2";

message Person {
    required int64 id = 1;
    required string name = 2;
    optional string email = 3;
}
syntax = "proto2"; 为定义使用的版本号, 目前常用版本proto2/proto3
message是消息定义的关键字,等同于C++/Swift中的struct/class,或是Java中的class
Person为消息的名字,等同于结构体名或类名
required前缀表示该字段为必要字段,既在序列化和反序列化之前该字段必须已经被赋值
optional前缀表示该字段为可选字段, 既在序列化和反序列化时可以没有被赋值
repeated通常被用在数组字段中
int64和string分别表示整型和字符串型的消息字段
id和name和email分别表示消息字段名,等同于Swift或是C++中的成员变量名
标签数字1和2则表示不同的字段在序列化后的二进制数据中的布局位置, 需要注意的是该值在同一message中不能重复
enum UserStatus {
    OFFLINE = 0;  //表示处于离线状态的用户
    ONLINE = 1;   //表示处于在线状态的用户
}

message UserInfo {
    required int64 acctID = 1;
    required string name = 2;
    required UserStatus status = 3;
}
enum UserStatus {
    OFFLINE = 0;
    ONLINE = 1;
}
message UserInfo {
    required int64 acctID = 1;
    required string name = 2;
    required UserStatus status = 3;
}

message LogonRespMessage {
    required LoginResult logonResult = 1;
    required UserInfo userInfo = 2;
}
protoc person.proto --swift_out="./"
// 1.创建UserInfo类型
let user = UserInfo.Builder()
user.acctID = Int64(1)
user.name = "Bob"
user.status = .ONLINE
// 2.获取对应的data
let userData = (try! user.build()).data()
let user = try! UserInfo.parseFrom(data: data)
上一篇 下一篇

猜你喜欢

热点阅读