【问题标题】:Send JSON dictionary and Image with Socket.io使用 Socket.io 发送 JSON 字典和图像
【发布时间】:2020-09-01 09:10:34
【问题描述】:

我想从 socket.io 将此 JSON 发送到我的 iOS 应用程序,我已经搜索过但没有得到任何完美的答案,这是我想分享给客户端应用程序的 JSON,我该如何发出这个?

{
    "message_id": "001",
    "type": ["add", "remove"],
    "student": {
        "id": "0001",
        "name": "john",
        "standard": "11",
    },
    "profile": {
        "thumb": Image (base64-encoded),
    }
}

有什么方法可以分享吗?我怎样才能做到这一点?我是socket.io的新手,请帮忙。 谢谢!

【问题讨论】:

    标签: ios swift express socket.io


    【解决方案1】:

    您可以使用以下客户端来接收您从服务器发出的 json 数据。

    https://github.com/socketio/socket.io-client-swift

    在服务器中:

    var socket = require( 'socket.io' );
    var express = require( 'express' );
    var http = require( 'http' );
    var app = express();
    var server = http.createServer( app );
    var io = socket.listen( server );
    
    
    io.sockets.on( 'connection', function() {
    
    console.log( "Client connected" );
    
    let data = {
        "message_id": "001",
        "type": ["add", "remove"],
        "student": {
            "id": "0001",
            "name": "john",
            "standard": "11",
        },
        "profile": {
            "thumb": Image (base64-encoded),
        }
    };
    
    socket.emit( 'message', data );
    
      });
    
    });
    
    server.listen(8080);
    

    您可以在以下链接中找到向客户端发送消息的各种选项

    https://socket.io/docs/emit-cheatsheet/

    在您的 IOS 客户端中:

    import Foundation
    
    let socket = SocketIOClient(socketURL: "localhost:8080")
    socket.on("message") { data, ack in
        println("Message for you! \(data?[0])")
        ack?("I got your message, and I'll send my response") 
        socket.emit("response", "Hello!")
    }
    socket.connect()
    

    【讨论】:

    • 感谢回复,如何在 JSON 中添加图片(base 64)?
    • 不建议在 JSON 对象中发送 base64 字符串。这是一个不好的做法。或者,您可以以 JSON 格式发送图像的一些 url,以便以后可以使用该图像。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    相关资源
    最近更新 更多