/*初始化客户端,并连接服务器*/
func connectServer(addr: String,port: Int){
print(addr,port)
_socketClient = TCPClient(addr: addr ,port: port)
//连接服务器
let (success,msg) = (_socketClient?.connect(timeout: 5))!
if success {
dispatch_sync(dispatch_get_main_queue(), {
self._connectBtn?.setTitle("已连接", forState: .Normal)
self._connectBtn?.userInteractionEnabled = false
})
//发送用户名
let msgBegin =["cmd":"nickname","nickname":_userD.objectForKey("Username") as! String]
sendMsg(msgBegin)
}else{
print("error connect")
}
//持续接收服务器发来的信息
while true {
if let msg = readmsg(){
print("收到服务器贺电")
self.processMessage(msg)
}else{
dispatch_async(dispatch_get_main_queue(), {
//self.disconnect()
})
break
}
}
}
//send msg
func sendMsg(msg: NSDictionary){
let msgdata = try? NSJSONSerialization.dataWithJSONObject(msg, options: .PrettyPrinted)
var len: Int32 = Int32((msgdata?.length)!)
let data: NSMutableData = NSMutableData(bytes: &len,length: 4)
_socketClient?.send(data: data)
_socketClient?.send(data: msgdata!)
}
func sendMsg1(msg: NSData){
_socketClient?.send(data: msg)
}
var readLength = 0
var buffArr:[UInt8]?
//用于读取并解析服务端发来的消息
//解析接收到的消息
func readmsg()->NSDictionary?{
//read 4 byte int as type
if let data=self._socketClient!.read(4){
if data.count==4{
let ndata = NSData(bytes: data, length: data.count)
var len: Int32 = 0
//获得DATA总长
ndata.getBytes(&len, length: data.count)
buffArr =[UInt8]()
var buff = self._socketClient!.read(Int(len))
if buff != nil {
//if Int32(buff.count) == len {
//print("buffcount = ",buff.count,"buff = ",buff)
//
//
//}else if Int32(buff.count) < len {
//
//}else{
//print("read error!!!!!!!!!!!!!!!!")
//}
print("len = ",len)
print("buff = ",buff!.count)
if Int32(buff!.count) < len {
while Int32(readLength) < len {
for int8Buff in buff! {
//print(int8Buff)
buffArr?.append(int8Buff)
}
print("len = ",len)
print("buff = ",buff!.count)
readLength += buff!.count
//len -= Int32(buff.count)
buff = (self._socketClient?.read(Int(len-Int32(readLength))))
print("readLength = ",readLength)
}
}
//print(buffArr!)
print(buffArr?.count)
var msgd: NSData?
if buffArr?.count == 0 {
msgd = NSData(bytes: buff!, length: buff!.count)
}else{
msgd = NSData(bytes: buffArr!, length: buffArr!.count)
}
//print(msgd)
//let str = NSString.init(data: msgd!, encoding: NSUTF8StringEncoding)
//print(str!)
let msgi: NSDictionary = (try?NSJSONSerialization.JSONObjectWithData(msgd!, options: .AllowFragments)) as! NSDictionary
readLength = 0
print(msgi)
return msgi
}
}
}
return nil
}
//处理服务器返回的消息
func processMessage(msg: NSDictionary){
let cmd:String = msg["cmd"] as! String
switch(cmd){
case "msg":
print((msg["from"] as! String) + ": " + (msg["content"] as! String) + "\n")
//if如果from是自己的username那么用writeDataArr接elsereadDataArr接
let name = (msg["from"] as! String)
if (_userD.objectForKey("Username") == nil) {
return
}
if name == (_userD.objectForKey("Username")) as! String {
let date = NSDate()
let str = Utilities.getDateFormat(date, str: "HH:mm")
let dict = ["date":str,"str":(msg["content"] as! String) + " :" + (msg["from"] as! String),"wor":"w","cmd":"str","fontSize":msg["fontSize"] as! String,"r":msg["r"] as! String,"g":msg["g"] as! String,"b":msg["b"] as! String]
_writeData?.addObject(dict)
reloadData()
}else{
let date = NSDate()
let str = Utilities.getDateFormat(date, str: "HH:mm:ss")
let dict = ["date":str,"str":(msg["from"] as! String) + ": " + (msg["content"] as! String),"wor":"r","cmd":"str","fontSize":msg["fontSize"] as! String,"r":msg["r"] as! String,"g":msg["g"] as! String,"b":msg["b"] as! String]
_readData?.addObject(dict)
reloadData()
}
case "setFont_color":
print(msg)
_name = msg["Username"] as! String
_fontSize = (msg["font"] as! NSString).integerValue
let r = (msg["r"] as! NSString).floatValue
let g = (msg["g"] as! NSString).floatValue
let b = (msg["b"] as! NSString).floatValue
print("name = ",_name,"fontsize = ",_fontSize,"------",r,g,b)
_color = UIColor.init(red: CGFloat(r), green: CGFloat(g), blue: CGFloat(b), alpha: 1)
case "image":
let arr = NSArray.init(object: msg)
if isFirst {
_writeData?.removeObjectAtIndex(0)
_readData?.removeObjectAtIndex(0)
self._dataArr?.removeAllObjects()
isFirst = false
}
_dataArr?.addObject(arr)
_isInputImage = 1
dispatch_sync(dispatch_get_main_queue(), {
self._tableView?.reloadData()
})
default:
print(msg)
}
}