打开TCP连接,发送多条消息,并关闭流后
问题描述:
我怎样才能改变这种代码:打开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();
}
}
为了能够连接到插座事件(比如说按钮点击),将消息发送到端口上事件,然后关闭事件中的套接字连接。
谢谢
答
如果你想保持连接,你必须使Socket成为一个类变量。 然后,您可以从该类中的每个方法访问它。
当您实例化类时打开套接字并在完成发送/接收时关闭。
请注意,您可能需要引入一个线程来保持EDT从网络通信中清除。
你有什么问题?它做到了这一切。只需在click-Listener中调用它即可。或者更好地在点击监听器中产生一个线程,并让这个线程调用它。 – Fildor 2014-09-20 16:09:58
每次我发送命令套接字后,收到答案。我发送命令的机器无法处理常量连接/断开连接。机器只能接受一个连接,并且在连接关闭后,机器在端口关闭后不能接受任何连接6秒钟。 – BetterNerf 2014-09-20 16:16:35