SocketServer

//服务器端口

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

}

//循环接收消息

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)

}

//发送消息

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)

}

//关闭连接

funckill(){

self.tcpClient!.close()

}

}

//服务端

classMyServer:NSObject{

varclients:[ChatUser] = []

varserver:TCPServer=TCPServer(addr:"192.168.224.48", port:port)//127.0.0.1

varserverRuning:Bool=false

//启动服务

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...")

}

//停止服务

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)

}

}

你可能感兴趣的:(SocketServer)