Thursday, 20 April 2017

Swift3 Use socket.io to load image from server

I'm trying to use Socket.IO-Client-Swift in swift3 to load an image from server written in Node.js. However, it fails.

Here is server code written in Node.js :

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs'); // required for file serving

http.listen(8080, function(){
  console.log('listening on *:8080');
});

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

// trying to serve the image file from the server
io.on('connection', function(socket){
  fs.readFile(__dirname + '/images/image.jpg', function(err, buf){
    socket.emit('getPhoto', { image: true, buffer: buf.toString('base64') });
    console.log('image file is initialized');
  });
});

Here is client code written in swift 3:

import UIKit
import SocketIO

class transformedTableViewController: UITableViewController {

    let socket = SocketIOClient(socketURL: URL(string: "http://localhost:8080")!, config: [.log(true), .forcePolling(true)])
    var placeholderImage: NSData? = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        loadTransformedImage(imageData: placeholderImage)
        self.socket.connect()

    }

    func loadTransformedImage(imageData: NSData!) -> Void {
        self.socket.on("connect") {data, ack in
            print("socket connected")
        }

        self.socket.on("getPhoto") { data, ack in    
            if let buffer = data[0] as? NSData {
                let image = UIImage(data: buffer as Data)
                let loadedImageView = UIImageView(image: image!)
                loadedImageView.frame = CGRect(origin: CGPoint(x: 30,y :50), size: CGSize(width: 110, height: 110))
                self.view.addSubview(loadedImageView)
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

And here is the error:

(It keeps repeating these error lines...)

LOG SocketEngine: Writing poll: has data: false

LOG SocketEnginePolling: Sending poll: as type: 2

LOG SocketEnginePolling: Created POST string: 1:2

LOG SocketEnginePolling: POSTing

LOG SocketEnginePolling: Doing polling request

LOG SocketEnginePolling: Got polling response

LOG SocketEnginePolling: Doing polling request

LOG SocketEngine: Got message: 3

It seems client didn't catch the data send from server. Any comment is appreciated!!!



via GuanJhen Su

No comments:

Post a Comment