JAVA: json + websocket

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12957440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:58:16  来源:igfitidea点击:

JAVA: json + websocket

javajsonwebsocket

提问by ashur

I'm creating with friend programming project. We splitted this in two parts, I'm responsible for client( simple window application ), he made server. I'm supposed to send JSON objects to his server with help of websocket ( he gave me info, what I should send http://pastebin.com/dmYBtN25). I know how to create json objects, but problem for me is how to use websocket lib combined with json( currently I'm using weberknecht and json-lib ). Below is an example I found that may be base for my client. I would be greatfull for tips and help or just simple example how to do that.

我正在与朋友编程项目一起创建。我们把它分成两部分,我负责客户端(简单的窗口应用程序),他负责服务器。我应该在 websocket 的帮助下将 JSON 对象发送到他的服务器(他给了我信息,我应该发送什么http://pastebin.com/dmYBtN25)。我知道如何创建 json 对象,但对我来说问题是如何将 websocket lib 与 json 结合使用(目前我正在使用 weberknecht 和 json-lib )。下面是我发现的一个例子,它可能是我客户的基础。我会很高兴获得提示和帮助,或者只是如何做到这一点的简单示例。

import java.net.URI;
import java.net.URISyntaxException;

import de.roderick.weberknecht.WebSocket;
import de.roderick.weberknecht.WebSocketConnection;
import de.roderick.weberknecht.WebSocketEventHandler;
import de.roderick.weberknecht.WebSocketException;
import de.roderick.weberknecht.WebSocketMessage;


public class App {
    public static void main(String[] args) {

    try {
        URI url = new URI("ws://127.0.0.1/test");
        WebSocket websocket = new WebSocketConnection(url);

        // Register Event Handlers

        websocket.setEventHandler(new WebSocketEventHandler() {
            public void onOpen() {
                System.out.println("--open");
            }

            public void onMessage(WebSocketMessage message) {
                System.out.println("--received message: "
                        + message.getText());
            }

            public void onClose() {
                System.out.println("--close");
            }
        });

        // Establish WebSocket Connection
        websocket.connect();

        // Send UTF-8 Text
        websocket.send("hello world");

        // Close WebSocket Connection
        websocket.close();
    } catch (WebSocketException wse) {
        wse.printStackTrace();
    } catch (URISyntaxException use) {
        use.printStackTrace();
    }
}

}

}

回答by Jonas Adler

have you tried:

你有没有尝试过:

websocket.send("{\"firstName\": \"John\"}" /* stick your JSON here */);

If you know how to create JSON that should do it.

如果您知道如何创建应该这样做的 JSON。

Exmaple of how you could create the JSON with google gson:

如何使用 google gson 创建 JSON 的示例:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * @author jadlr
 */
public class UserConnected {

private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();

private final int event;
private final String cookie;
private final From from;
private final Channel channel;

public UserConnected(int event, String cookie, From from, Channel channel) {
    this.from = from;
    this.cookie = cookie;
    this.event = event;
    this.channel = channel;
}

public int getEvent() {
    return event;
}

public String getCookie() {
    return cookie;
}

public From getFrom() {
    return from;
}

public String toJson() {
    return GSON.toJson(this, UserConnected.class);
}

public static class From {

    private final int id;
    private final String userId;

    public From(int id, String userId) {
        this.id = id;
        this.userId = userId;
    }

    public int getId() {
        return id;
    }

    public String getUserId() {
        return userId;
    }

}

public static class Channel {

    private final int id;
    private final String name;

    public Channel(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

}

public static void main(String[] args) {

    UserConnected userConnected = new UserConnected(0, "cookie123", new From(1, "user"), new Channel(1, "channel"));
    System.out.println(userConnected.toJson());

}

}