I'm trying to write a sample about the Bonjour service and a simple socket I/O stream.
What I can currently do, is:
- Publish a service, and scan it.
- Create an I/O stream socket between two devices or the simulator.
After the socket is connected, I got a problem with sending text to the service.
@IBAction func sendMessage(sender:AnyObject!){
if (self.outputStream == nil){
print("Connection not create yet ! =====> Return")
return
}
let s : String = (self.textfield?.text)!
print("\(self.outputStream) ==> Pass Data : \(s)")
let data: NSData = s.data(using: String.Encoding.utf8)!
self.outputStream?.open()
self.outputStream?.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
self.outputStream?.close()
//Service no any response or log
}
When the button's pressed, nothing seems to happen, and I'm wondering if it writes or not.
UPDATE
There was a problem with the client receiving the information. A run loop was needed.
func netService(_ sender: NetService, didAcceptConnectionWith inputStream: InputStream, outputStream: NSOutputStream) {
self.receiveTextView?.text = "Accept Connection Success"
print("netService : \(sender) didAcceptConnectionWith Input Stream : \(inputStream) , Output Stream : \(outputStream)")
inputStream.delegate = self
outputStream.delegate = self
inputStream.schedule(in: RunLoop.main(), forMode: RunLoopMode.defaultRunLoopMode)
outputStream.schedule(in: RunLoop.main(), forMode: RunLoopMode.defaultRunLoopMode)
inputStream.open()
outputStream.open()
}
The data is then received in the Stream delegate.
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
case Stream.Event.hasBytesAvailable:
NSLog("HasBytesAvailable")
var buffer = [UInt8](repeating:0, count:4096)
let inputStream = aStream as? InputStream
while ((inputStream?.hasBytesAvailable) != false){
let len = inputStream?.read(&buffer, maxLength: buffer.count)
if(len > 0){
let output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
if (output != ""){
NSLog("Server Received : %@", output!)
self.receiveTextView?.text = output as String?
}
}else{
break
}
}
break
default:
NSLog("unknown.")
}
}