//服務(wù)器端口
varport =6666
//客戶端管理類
classChatUser:NSObject{
vartcpClient:TCPClient?
varusername:String=""
varsocketServer:MyServer?
//解析接收到的消息
funcreadMsg()->NSDictionary?{
//read 4 byte int as type
ifletdata=self.tcpClient!.read(4){
ifdata.count==4{
letndata=NSData(bytes: data, length: data.count)
varlen:Int32=0
ndata.getBytes(&len, length: data.count)
ifletbuff=self.tcpClient!.read(Int(len)){
letmsgd:NSData=NSData(bytes: buff, length: buff.count)
letmsgi:NSDictionary=(try!
NSJSONSerialization.JSONObjectWithData(msgd,
options: .MutableContainers))as!NSDictionary
returnmsgi
}
}
}
returnnil
}
//循環(huán)接收消息
funcmessageloop(){
whiletrue{
ifletmsg=self.readMsg(){
self.processMsg(msg)
}else{
self.removeme()
break
}
}
}
//處理收到的消息
funcprocessMsg(msg:NSDictionary){
ifmsg["cmd"]as!String=="nickname"{
self.username= msg["nickname"]as!String
}
self.socketServer!.processUserMsg(user:self, msg: msg)
}
//發(fā)送消息
funcsendMsg(msg:NSDictionary){
letjsondata=try?NSJSONSerialization.dataWithJSONObject(msg, options:
NSJSONWritingOptions.PrettyPrinted)
varlen:Int32=Int32(jsondata!.length)
letdata:NSMutableData=NSMutableData(bytes: &len, length:4)
self.tcpClient!.send(data: data)
self.tcpClient!.send(data: jsondata!)
}
//移除該客戶端
funcremoveme(){
self.socketServer!.removeUser(self)
}
//關(guān)閉連接
funckill(){
self.tcpClient!.close()
}
}
//服務(wù)端
classMyServer:NSObject{
varclients:[ChatUser] = []
varserver:TCPServer=TCPServer(addr:"192.168.224.48", port:port)//127.0.0.1
varserverRuning:Bool=false
//啟動服務(wù)
funcstart() {
server.listen()
self.serverRuning=true
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0), {
whileself.serverRuning{
letclient=self.server.accept()
ifletc=client{
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0), {
self.handleClient(c)
})
}
}
})
self.log("server started...")
}
//停止服務(wù)
funcstop() {
self.serverRuning=false
self.server.close()
//forth close all client socket
forc:ChatUserinself.clients{
c.kill()
}
self.log("server stoped...")
}
//處理連接的客戶端
funchandleClient(c:TCPClient){
self.log("new client from:"+c.addr)
letu=ChatUser()
u.tcpClient= c
clients.append(u)
u.socketServer=self
u.messageloop()
}
//處理各消息命令
funcprocessUserMsg(user u:ChatUser,msg m:NSDictionary){
self.log("\(u.username)[\(u.tcpClient!.addr)]cmd:"+(m["cmd"]as!String))
//boardcast message
varmsgtosend=[String:String]()
letcmd = m["cmd"]as!String
ifcmd=="nickname"{
msgtosend["cmd"]="join"
msgtosend["nickname"]=u.username
msgtosend["addr"]=u.tcpClient!.addr
}elseif(cmd=="msg"){
msgtosend["cmd"]="msg"
msgtosend["from"]=u.username
msgtosend["content"]=(m["content"]as!String)
}elseif(cmd=="leave"){
msgtosend["cmd"]="leave"
msgtosend["nickname"]=u.username
msgtosend["addr"]=u.tcpClient!.addr
}elseif(cmd=="setFont_color"){
msgtosend["cmd"]="setFont_color"
msgtosend["font"]=m["fontSize"]as?String
msgtosend["r"]=m["r"]as?String
msgtosend["g"]=m["g"]as?String
msgtosend["b"]=m["b"]as?String
msgtosend["Username"]=m["Username"]as?String
//msgtosend["color"]=
}
foruser:ChatUserinself.clients{
//if u~=user{
print(msgtosend)
user.sendMsg(msgtosend)
//}
}
}
//移除用戶
funcremoveUser(u:ChatUser){
self.log("remove user\(u.tcpClient!.addr)")
ifletpossibleIndex=self.clients.indexOf(u){
self.clients.removeAtIndex(possibleIndex)
self.processUserMsg(user: u, msg: ["cmd":"leave"])
}
}
//日志打印
funclog(msg:String){
print(msg)
}
}