【问题标题】:Java how to send active connection to other classJava如何将活动连接发送到其他类
【发布时间】:2021-06-16 05:52:50
【问题描述】:

我想向其他班级发送活动连接,但我不知道我是否可以这样做。

我在客户端有方法和构造函数

 public ChatClient(String serverName, int serverPort) {
    this.serverName = serverName;
    this.serverPort = serverPort;
}

public boolean connect() {
    try {
        this.socket = new Socket(serverName, serverPort);
        System.out.println("Client port: " + socket.getLocalPort());
        this.serverOut = socket.getOutputStream();
        this.serverIn = socket.getInputStream();
        this.bufferedIn = new BufferedReader(new InputStreamReader(serverIn));
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

在我的另一堂课中调用它

        public LoginUserWindow(){
        JFrame f= new JFrame("Panel Example");

        this.client = new ChatClient("localhost", 2137);
        client.connect();
       }

现在我已经连接到我的服务器,我想用同样的连接调用另一个类

 loginButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {

           AnotherClass anotherClass = new AnotherClass(here must be active connection i think);
   }



 });

有人知道我应该怎么做或如何做得更好?

【问题讨论】:

  • 只保存为属性?
  • 你能举个例子吗?

标签: java multithreading server connection client


【解决方案1】:

现在我已经连接到我的服务器,我想用相同的连接调用另一个类

对于另一个类来处理服务器上的特定连接,该类需要在完成该工作所需的所有字段中传递。通常,服务器调用serverSocket.accept(),它返回一个Socket,然后可以将其传递给将处理连接的类。

这是一些伪代码:

ExecutorService threadPool = Executors.newCachedThreadPool();
while (running) {
   Socket socket = serverSocket.accept();
   threadPool.submit(new ClientHandler(socket));
}
// stop the thread pool – you can do shutdownNow() to interrupt the current clients
threadPool.shutdown();
// wait for all of the existing clients to finish
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

连接在服务器上被接受,并将它们添加到线程池中以并行运行。 ClientHandler 应该实现 Runnable。在ClientHandler 内部,它应该执行所有操作来为该特定连接提供服务。

服务器将继续接受套接字上的连接,直到 running 标志设置为 false 或 serverSocket 关闭等。

希望这里有所帮助。

【讨论】:

    猜你喜欢
    • 2017-03-03
    • 2023-03-03
    • 2019-05-21
    • 2016-04-08
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    相关资源
    最近更新 更多