gpt4 book ai didi

javax.websocket 客户端简单示例

转载 作者:IT老高 更新时间:2023-10-28 11:35:49 30 4
gpt4 key购买 nike

谁能给我提供一个非常简单的使用 javax.websocket 的 websocket 客户端示例?

我想连接到 websocket (ws://socket.example.com:1234),发送消息(添加 channel )并收听消息。所有消息(发送和收听)都是 JSON 格式。

顺便说一句,这个库是最适合简单 websocket 通信的库吗?

最佳答案

我在这里找到了一个使用 javax.websocket 的好例子:

http://www.programmingforliving.com/2013/08/jsr-356-java-api-for-websocket-client-api.html

这里的代码基于上面链接的示例:

TestApp.java:

package testapp;

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

public class TestApp {

public static void main(String[] args) {
try {
// open websocket
final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI("wss://real.okcoin.cn:10440/websocket/okcoinapi"));

// add listener
clientEndPoint.addMessageHandler(new WebsocketClientEndpoint.MessageHandler() {
public void handleMessage(String message) {
System.out.println(message);
}
});

// send message to websocket
clientEndPoint.sendMessage("{'event':'addChannel','channel':'ok_btccny_ticker'}");

// wait 5 seconds for messages from websocket
Thread.sleep(5000);

} catch (InterruptedException ex) {
System.err.println("InterruptedException exception: " + ex.getMessage());
} catch (URISyntaxException ex) {
System.err.println("URISyntaxException exception: " + ex.getMessage());
}
}
}

WebsocketClientEndpoint.java:

package testapp;

import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

/**
* ChatServer Client
*
* @author Jiji_Sasidharan
*/
@ClientEndpoint
public class WebsocketClientEndpoint {

Session userSession = null;
private MessageHandler messageHandler;

public WebsocketClientEndpoint(URI endpointURI) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, endpointURI);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

/**
* Callback hook for Connection open events.
*
* @param userSession the userSession which is opened.
*/
@OnOpen
public void onOpen(Session userSession) {
System.out.println("opening websocket");
this.userSession = userSession;
}

/**
* Callback hook for Connection close events.
*
* @param userSession the userSession which is getting closed.
* @param reason the reason for connection close
*/
@OnClose
public void onClose(Session userSession, CloseReason reason) {
System.out.println("closing websocket");
this.userSession = null;
}

/**
* Callback hook for Message Events. This method will be invoked when a client send a message.
*
* @param message The text message
*/
@OnMessage
public void onMessage(String message) {
if (this.messageHandler != null) {
this.messageHandler.handleMessage(message);
}
}

@OnMessage
public void onMessage(ByteBuffer bytes) {
System.out.println("Handle byte buffer");
}

/**
* register message handler
*
* @param msgHandler
*/
public void addMessageHandler(MessageHandler msgHandler) {
this.messageHandler = msgHandler;
}

/**
* Send a message.
*
* @param message
*/
public void sendMessage(String message) {
this.userSession.getAsyncRemote().sendText(message);
}

/**
* Message handler.
*
* @author Jiji_Sasidharan
*/
public static interface MessageHandler {

public void handleMessage(String message);
}
}

关于javax.websocket 客户端简单示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26452903/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com