답변:
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);
}
}
/**
* 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);
}
}
TooTallNate에는 간단한 클라이언트 측 https://github.com/TooTallNate/Java-WebSocket이 있습니다.
dist 폴더의 java_websocket.jar을 프로젝트에 추가하기 만하면됩니다.
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_10;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;
WebSocketClient mWs = new WebSocketClient( new URI( "ws://socket.example.com:1234" ), new Draft_10() )
{
@Override
public void onMessage( String message ) {
JSONObject obj = new JSONObject(message);
String channel = obj.getString("channel");
}
@Override
public void onOpen( ServerHandshake handshake ) {
System.out.println( "opened connection" );
}
@Override
public void onClose( int code, String reason, boolean remote ) {
System.out.println( "closed connection" );
}
@Override
public void onError( Exception ex ) {
ex.printStackTrace();
}
};
//open websocket
mWs.connect();
JSONObject obj = new JSONObject();
obj.put("event", "addChannel");
obj.put("channel", "ok_btccny_ticker");
String message = obj.toString();
//send message
mWs.send(message);
// 그리고 websocket을 닫습니다.
mWs.close();
Arun Gupta의이 Java EE 7 예제를 살펴보십시오.
나는 그것을 github에서 포크했다 .
본관
/**
* @author Arun Gupta
*/
public class Client {
final static CountDownLatch messageLatch = new CountDownLatch(1);
public static void main(String[] args) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://echo.websocket.org:80/";
System.out.println("Connecting to " + uri);
container.connectToServer(MyClientEndpoint.class, URI.create(uri));
messageLatch.await(100, TimeUnit.SECONDS);
} catch (DeploymentException | InterruptedException | IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
ClientEndpoint
/**
* @author Arun Gupta
*/
@ClientEndpoint
public class MyClientEndpoint {
@OnOpen
public void onOpen(Session session) {
System.out.println("Connected to endpoint: " + session.getBasicRemote());
try {
String name = "Duke";
System.out.println("Sending message to endpoint: " + name);
session.getBasicRemote().sendText(name);
} catch (IOException ex) {
Logger.getLogger(MyClientEndpoint.class.getName()).log(Level.SEVERE, null, ex);
}
}
@OnMessage
public void processMessage(String message) {
System.out.println("Received message in client: " + message);
Client.messageLatch.countDown();
}
@OnError
public void processError(Throwable t) {
t.printStackTrace();
}
}
다음은 간단한 예입니다. http://www.pretechsol.com/2014/12/java-ee-websocket-simple-example.html 다운로드하여 테스트 할 수 있습니다 .
이 라이브러리 org.java_websocket 사용
먼저 build.gradle에서 해당 라이브러리를 가져와야합니다.
repositories {
mavenCentral()
}
그런 다음 종속성에 구현 추가 {}
implementation "org.java-websocket:Java-WebSocket:1.3.0"
그런 다음이 코드를 사용할 수 있습니다.
활동에서 Websocketclient에 대한 객체를 다음과 같이 선언하십시오.
private WebSocketClient mWebSocketClient;
그런 다음 콜백 에이 메서드를 추가하십시오.
private void ConnectToWebSocket() {
URI uri;
try {
uri = new URI("ws://your web socket url");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
}
@Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textView = (TextView)findViewById(R.id.edittext_chatbox);
textView.setText(textView.getText() + "\n" + message);
}
});
}
@Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
@Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
내 프로젝트에 Spring 4.2가 있고 많은 SockJS Stomp 구현이 일반적으로 Spring Boot 구현과 잘 작동합니다. Baeldung의이 구현은 작동 했습니다 (Spring 4.2에서 5로 변경하지 않고 나를 위해). 그의 블로그에 언급 된 종속성을 사용한 후에도 여전히 ClassNotFoundError가 발생했습니다. 수정하기 위해 아래 종속성을 추가했습니다.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>