Java 打开TCP连接,发送多条消息,稍后关闭流

Java 打开TCP连接,发送多条消息,稍后关闭流,java,tcp,Java,Tcp,如何更改此代码: public class bingoMachineControl { void sendCommand(String command) throws IOException { String ipaddress = "192.168.0.2"; Socket commandSocket = null; // PrintWriter out = null; BufferedWriter out = null; BufferedReader in =

如何更改此代码:

public class bingoMachineControl {
void sendCommand(String command) throws IOException {
    String ipaddress = "192.168.0.2";
   Socket commandSocket = null;
//      PrintWriter out = null;
  BufferedWriter out = null;
  BufferedReader in = null;
  BufferedWriter outToDetailFile = null;
  FileWriter fstream = null;
  String version = "";
  int numberOfBallsInGame;
  int ledCycleState = 1;


         commandSocket = new Socket(ipaddress, 7420);

  //          out = new PrintWriter(commandSocket.getOutputStream(), true);
      out = new BufferedWriter(new OutputStreamWriter(commandSocket.getOutputStream()));
      in = new BufferedReader(new InputStreamReader(commandSocket.getInputStream()));
          out.write("c");out.flush();
          out.write(command);out.flush();

                 String message = in.readLine();

     out.close();
      in.close();
      commandSocket.close();

}
}
为了能够在事件时连接到套接字(比如说单击按钮),请在事件时向端口发送消息,然后在事件时关闭套接字连接


谢谢

如果要保持连接,必须将套接字设为类变量。 然后可以从该类中的每个方法访问它

实例化类时打开套接字,完成发送/接收后关闭套接字


请注意,您可能需要引入一个线程来保持EDT与网络通信的清洁。

您使用的方法有什么问题?它做到了这一切。只需在click Listener中调用它。或者最好在click listener中生成一个线程,并让该线程调用它。每次我发送命令时,套接字在收到应答后关闭。我向其发送命令的机器无法处理持续的连接/断开。机器只能接受一个连接,在连接关闭后,在端口关闭后的6秒钟内,机器无法接受任何连接。