2014-09-20 86 views
0

我怎樣才能改變這種代碼:打開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(); 

} 
} 

爲了能夠連接到插座事件(比如說按鈕點擊),將消息發送到端口上事件,然後關閉事件中的套接字連接。

謝謝

+0

你有什麼問題?它做到了這一切。只需在click-Listener中調用它即可。或者更好地在點擊監聽器中產生一個線程,並讓這個線程調用它。 – Fildor 2014-09-20 16:09:58

+0

每次我發送命令套接字後,收到答案。我發送命令的機器無法處理常量連接/斷開連接。機器只能接受一個連接,並且在連接關閉後,機器在端口關閉後不能接受任何連接6秒鐘。 – BetterNerf 2014-09-20 16:16:35

回答

0

如果你想保持連接,你必須使Socket成爲一個類變量。 然後,您可以從該類中的每個方法訪問它。

當您實例化類時打開套接字並在完成發送/接收時關閉。

請注意,您可能需要引入一個線程來保持EDT從網絡通信中清除。

相關問題