manager管家 --- 交给client处理 其实还是服务器在处理---client中block回调还是让服务器处理而已
服务器
1> 创建Socket
2> 绑定端口
3> 监听listen
4> 接受客户端的链接(accept) socket
* 阻塞式的函数
*/
如果离开房间
client.callback = {[unowned self] (isLeave, data, client) in
// 1.是否需要移动客户端
if isLeave {
if let index = self.clients.index(of: client) {
self.clients.remove(at: index)
client.tcpClient.close()
}
}
// 2.将消息转发出去
for c in self.clients {
c.tcpClient.send(data: data)
}
如果没有正在运行 也移除
client.removeClientCallback = {[unowned self] (client) in
if let index = self.clients.index(of: client) {
self.clients.remove(at: index)
client.tcpClient.close()
}
}
+++++++++++++++++++++++++++++++++++++++++++++++++++
import Cocoa
class IMServerManager: NSObject {
fileprivate lazy var tcpServer : TCPServer = TCPServer(addr: "0.0.0.0", port: 2828)
fileprivate lazy var clients : [IMClient] = [IMClient]()
}
extension IMServerManager {
func startRunning() {
// 1.监听客户端的链接
tcpServer.listen()
// 2.接受客户端的链接
DispatchQueue.global().async {
while true {
if let tcpClient = self.tcpServer.accept() {
DispatchQueue.global().async {
self.handleClient(tcpClient)
}
}
}
}
}
func stopRunning() {
}
}
extension IMServerManager {
fileprivate func handleClient(_ client : TCPClient) {
let client = IMClient(client: client)
clients.append(client)
client.callback = {[unowned self] (isLeave, data, client) in
// 1.是否需要移动客户端
if isLeave {
if let index = self.clients.index(of: client) {
self.clients.remove(at: index)
client.tcpClient.close()
}
}
// 2.将消息转发出去
for c in self.clients {
c.tcpClient.send(data: data)
}
}
client.removeClientCallback = {[unowned self] (client) in
if let index = self.clients.index(of: client) {
self.clients.remove(at: index)
client.tcpClient.close()
}
}
client.startReadMessage()
}
}
+++++++++++
import Cocoa
class IMClient: NSObject {
var tcpClient : TCPClient
var callback : ((Bool, Data, IMClient) -> Void)?
var removeClientCallback : ((IMClient) -> Void)?
fileprivate var isRunning : Bool = false
init(client : TCPClient) {
self.tcpClient = client
}
}
extension IMClient {
func startReadMessage() {
isRunning = true
while isRunning {
if let lengthByte = tcpClient.read(4) {
// 1.获取数据的长度
let lengthData = NSData(bytes: lengthByte, length: 4)
var length : Int = 0
lengthData.getBytes(&length, length: 4)
// 2.读取消息的类型
guard let typeBytes = tcpClient.read(2) else {
tcpClient.read(length)
continue
}
let typeData = NSData(bytes: typeBytes, length: 2)
var type : Int = 0
typeData.getBytes(&type, length: 2)
print(type)
// 3.获取具体的内容
guard let dataBytes = tcpClient.read(length) else {
return
}
let msgData = Data(bytes: dataBytes, count: length)
// 1> 判断是否是离开消息: 告诉其他人, 有人离开房间, 将该客户端从数组中移除
// 2> 其他消息, 直接转发给其他客户端
let isLeave = type == 1 ? true : false
callback?(isLeave, (lengthData as Data) + (typeData as Data) + msgData, self)
} else {
isRunning = false
removeClientCallback?(self)
}
}
网友评论