Lukas00990
2021-10-22 00:46
采纳率: 41.4%
浏览 73

java WebSocket, 如何只发一个信息,就停止。

用JAVA websocket 发信息,用的是tyrus 工具包。 client 端代码如下:

package websockets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.CountDownLatch;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.DeploymentException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import org.glassfish.tyrus.client.ClientManager;

@ClientEndpoint
public class ChatClientEndpoint {

    private static CountDownLatch latch;

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("--- Connected " + session.getId());
        try {
            session.getBasicRemote().sendText("Sk_execute");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @OnMessage
    public String onMessage(String message, Session session) {
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.println("--- Received: " + message);
            String userInput = bufferRead.readLine();
               CloseReason closeReason = null;
                this.onClose(session, closeReason);
                session.close();

            }
            return userInput;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("Session " + session.getId()
                + " closed because " + closeReason);
        //latch.countDown();
    }

    public static void main(String[] args) {
        latch = new CountDownLatch(1);
        ClientManager client = ClientManager.createClient();
        try {
            URI uri = new URI("ws://192.168.1.10:3000/");
            client.connectToServer(ChatClientEndpoint.class, uri);

            latch.await();

        } catch (DeploymentException | URISyntaxException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

我现在想实现,我client 发一个信号后,关闭线程。如何操作?现阶段的代码是 信息一直在发送。除此之外, @OnMessage 这个方法中的下面两行用不了。
this.onClose(session, closeReason);
session.close();

我想实现的是,client 收到一个信息后,关闭线程。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题