ash*_*hur 4 java json websocket
我正在与朋友编程项目一起创建。我们把它分成两部分,我负责客户端(简单的窗口应用程序),他负责服务器。我应该在 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();
}
}
Run Code Online (Sandbox Code Playgroud)
}
你有没有尝试过:
websocket.send("{\"firstName\": \"John\"}" /* stick your JSON here */);
Run Code Online (Sandbox Code Playgroud)
如果您知道如何创建应该这样做的 JSON。
如何使用 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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13913 次 |
| 最近记录: |