我想连接到服务器,ws://12.526.712.67:8000 / joker并被告知要建立连接,并使用WEBSOCKETS检查成功消息。然后我必须发布一个JSON数据和下一个请求并获得JSON响应。我不应该使用任何第三方框架。所以我得到了一个示例代码来完成这项工作,
class Handler :NSObject, StreamDelegate {
var inputStream: InputStream?
var outputStream: OutputStream?
var status = false;
var output = ""
var bufferSize = 1024;
var onComing:OnComing!
func connect(host: String, port: Int, onComing:@escaping OnComing) {
Stream.getStreamsToHost(withName: host, port: port, inputStream: &inputStream, outputStream: &outputStream)
if inputStream != nil && outputStream != nil {
inputStream!.delegate = self
outputStream!.delegate = self
self.onComing = onComing
inputStream!.schedule(in: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
outputStream!.schedule(in: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
inputStream!.open()
outputStream!.open()
print("successfully connected")
}
else {
print("connection unsuccessful")
}
}
func stream(_ aStream: Stream, handle eventCode: Stream.Event)
{
if aStream === inputStream {
switch eventCode {
case Stream.Event.errorOccurred:
print("input: ErrorOccurred: \(String(describing: aStream.streamError?.localizedDescription))")
break
case Stream.Event.openCompleted:
print("input: OpenCompleted")
break
case Stream.Event.hasBytesAvailable:
print("input: HasBytesAvailable")
print(Stream.Event.hasBytesAvailable)
print(Stream.Event.hasBytesAvailable.rawValue)
var buffer = [UInt8](repeating: 0, count: 4096)
while (inputStream?.hasBytesAvailable)!{
let len = inputStream?.read(&buffer, maxLength: buffer.count)
if(len! > 0){
let output = NSString(bytes: &buffer, length: len!, encoding: String.Encoding.utf8.rawValue)
if (output != ""){
print("server said: %@", output!)
}
} else {
print("empty string from stream")
}
}
break
case Stream.Event.hasSpaceAvailable:
print("input: hasSpaceAvailable")
break
default:
break
}
}
else {
print("unknown stuff happened")
}
}
func disconnect() {
if let stream = self.inputStream {
stream.close();
stream.remove(from: RunLoop.current, forMode: RunLoopMode.commonModes);
}
if let stream = self.outputStream {
stream.close();
stream.remove(from: RunLoop.current, forMode: RunLoopMode.commonModes);
}
self.inputStream = nil;
self.outputStream = nil;
}
func read() {
output = ""
var buffer = [UInt8](repeating: 0, count: bufferSize)
while (self.inputStream!.hasBytesAvailable) {
let bytesRead: Int = inputStream!.read(&buffer, maxLength: buffer.count)
if bytesRead >= 0 {
output += NSString(bytes: UnsafePointer(buffer), length: bytesRead, encoding: String.Encoding.ascii.rawValue)! as String
} else {
print("# Stream read() error")
}
}
self.onComing(output)
}
func write(message:String) {
let data = message.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
{
print(jsonArray)
let encodedDataArray = [UInt8]("\(jsonArray)\n".utf8)
self.outputStream?.write(encodedDataArray, maxLength: encodedDataArray.count)
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
}}
我使用方法
触发了这个类Handler.connect(host: "12.526.712.67", port: 8000, onComing: {_ in
print(OnComing.self)})
我在委托响应中获得连接成功,但是当我将json数据作为输入传递时,我得到了,
HTTP/1.1 400
Transfer-Encoding: chunked
Date: Fri, 16 Mar 2018 09:00:31 GMT
Connection: close
我做错了什么?我无法获得JSON响应或任何状态消息,&#34;服务器说:%@&#34;部分总是空的,为什么会这样?请帮我解决这个问题。