0

How can I change this code:

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();

}
}

To be able to connect to socket on event (let's say button click), send a message to port on event and then close the socket connection also on event.

Thank you

2
  • What is wrong with the method you have? It does all of that. Just call it in the click-Listener. Or better spawn a thread in the click-listener and have that one call it.
    – Fildor
    Sep 20, 2014 at 16:09
  • Every time i send command socket closes after recieveing answer. The machine i'm sending the commands to can't handle constant connects/disconnects. The machine can only accept one connection and after the connection closes machine can't accept any connections for 6 seconds after port close.
    – BetterNerf
    Sep 20, 2014 at 16:16

1 Answer 1

0

If you want to keep up the connection, you'll have to make the Socket a class variable. Then you can access it from each method in that class.

Open the socket when you instantiate the class and close when you are done with sending / receiving.

Mind that you might need to introduce a Thread for keeping the EDT clean from Network communication.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.