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

时间:2014-09-20 15:32:03

标签: 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 = 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();

}
}

为了能够在事件上连接到套接字(让按钮单击按钮),在事件上向端口发送消息,然后在事件上也关闭套接字连接。

谢谢

1 个答案:

答案 0 :(得分:0)

如果要保持连接,则必须使Socket成为类变量。 然后,您可以从该类中的每个方法访问它。

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

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