【问题标题】:How to control the printwriter from a separate method?如何从单独的方法控制打印机?
【发布时间】:2019-02-05 08:03:15
【问题描述】:

我正在构建自己的 GUI 程序,该程序可以通过平板电脑与我的电脑对话。我在java中完成了服务器端,但我的问题出在客户端。

我想通过单独的方法将数据从 PrintWriter 发送到服务器。 我已经完成了以下代码的发送(它发送'a'),但我不知道如何从单独的方法发送它。我相信这是一个我不理解的基本 Java 范围问题。非常感谢您的帮助。

我已经尝试将变量移动到其他范围内。

import java.io.*;
import java.net.*;

public class TestClient {

    public static void main(String[] args) {
        String hostName = "192.168.0.3";
        int portNumber = 6666;

        try (   //Connect to server on chosen port.
                Socket connectedSocket = new Socket(hostName, portNumber);
                //Create a printWriter so send data to server.
                PrintWriter dataOut = new PrintWriter(connectedSocket.getOutputStream(), true);

                BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))
            ) {
            //Send data to server.
            dataOut.println("a");

        }catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                hostName);
            System.exit(1);
        } 
    }

    public static void sendToServer() {
        //I want to control the print writer from this method.
        //I have failed i all the ways i have tried.

    }
}

【问题讨论】:

  • 尝试将PrintWriter 作为参数传递给该方法。

标签: java socket.io


【解决方案1】:

您可以将打印机代码(尝试尝试块)移动到 sendToServer 方法中并通过调用它

TestClient client = new TestClient();
client.sendToServer("this is a test");

当然 sendToServer 方法需要接受一个参数。更好的方法可能是将 main 方法放入 Starter 类,并将其与用于发送数据的 Client-Class 分离。

【讨论】:

  • 所以即使我已经连接了它,也可以尝试再次打开套接字。它不会使事情运行缓慢或什么?我认为每次发送新数据时都会不断要求它连接会出现问题。
  • 应该没问题。只是不要忘记在发送数据后手动关闭它。您可以在 try-catch 块中添加“finally{}”语句并调用 Socket.close();从那里。当您再次发送数据时,这将为另一个连接释放端口。
猜你喜欢
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2013-06-10
  • 2015-10-16
  • 1970-01-01
相关资源
最近更新 更多