import
UIKit
class
ViewController
:
UIViewController
{
@IBOutlet
weak
var
textFiled:
UITextField
!
@IBOutlet
weak
var
textView:
UITextView
!
var
socketServer:
MyTcpSocketServer
?
var
socketClient:
TCPClient
?
override
func
viewDidLoad() {
super
.viewDidLoad()
socketServer =
MyTcpSocketServer
()
socketServer?.start()
processClientSocket()
}
func
processClientSocket(){
socketClient=
TCPClient
(addr:
"localhost"
, port: 8080)
dispatch_async(dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_BACKGROUND
, 0), {
() ->
Void
in
func
readmsg()->
NSDictionary
?{
if
let
data=
self
.socketClient!.read(4){
if
data.count==4{
var
ndata=
NSData
(bytes: data, length: data.count)
var
len:
Int32
=0
ndata.getBytes(&len, length: data.count)
if
let
buff=
self
.socketClient!.read(
Int
(len)){
var
msgd:
NSData
=
NSData
(bytes: buff, length: buff.count)
var
msgi:
NSDictionary
=
NSJSONSerialization
.
JSONObjectWithData
(
msgd,
options: .
MutableContainers
, error:
nil
)
as
!
NSDictionary
return
msgi
}
}
}
return
nil
}
var
(success,msg)=
self
.socketClient!.connect(timeout: 5)
if
success{
dispatch_async(dispatch_get_main_queue(), {
self
.alert(
"connect success"
, after: {
})
})
var
msgtosend=[
"cmd"
:
"nickname"
,
"nickname"
:
"游客\(Int(arc4random()%1000))"
]
self
.sendMessage(msgtosend)
while
true
{
if
let
msg=readmsg(){
dispatch_async(dispatch_get_main_queue(), {
self
.processMessage(msg)
})
}
else
{
dispatch_async(dispatch_get_main_queue(), {
})
break
}
}
}
else
{
dispatch_async(dispatch_get_main_queue(), {
self
.alert(msg,after: {
})
})
}
})
}
@IBAction
func
sendMsg(sender:
AnyObject
) {
var
content=textFiled.text
var
message=[
"cmd"
:
"msg"
,
"content"
:content]
self
.sendMessage(message)
textFiled.text=
nil
}
func
sendMessage(msgtosend:
NSDictionary
){
var
msgdata=
NSJSONSerialization
.dataWithJSONObject(msgtosend,
options:
NSJSONWritingOptions
.
PrettyPrinted
, error:
nil
)
var
len:
Int32
=
Int32
(msgdata!.length)
var
data:
NSMutableData
=
NSMutableData
(bytes: &len, length: 4)
self
.socketClient!.send(data: data)
self
.socketClient!.send(data:msgdata!)
}
func
processMessage(msg:
NSDictionary
){
var
cmd:
String
=msg[
"cmd"
]
as
!
String
switch
(cmd){
case
"msg"
:
self
.textView.text =
self
.textView.text +
(msg[
"from"
]
as
!
String
) +
": "
+ (msg[
"content"
]
as
!
String
) +
"\n"
default
:
println
(msg)
}
}
func
alert(msg:
String
,after:()->(
Void
)){
var
alertview=
UIAlertView
(title:
""
, message: msg, delegate:
nil
,
cancelButtonTitle:
nil
)
alertview.show()
dispatch_after(dispatch_time(
DISPATCH_TIME_NOW
, 3), dispatch_get_main_queue(),{
alertview.dismissWithClickedButtonIndex(0, animated:
true
)
after()
})
}
override
func
didReceiveMemoryWarning() {
super
.didReceiveMemoryWarning()
}
}
请发表评论