我有一个Java客户端应用程序,通过这个应用程序,我可以与服务器应用程序通信。
我有一个简单的方法sendCommand,它将消息发送到服务器:
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 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();
//System.out.println(message);
out.close();
in.close();
commandSocket.close();
}
现在,因为服务器应用程序在20秒内不接受2个以上连接的机器上,我需要修改我的方法并用3种不同的方法“拆分”它(我认为)。 我的计划如下: 我想在一个线程中调用与服务器的连接,保持打开直到我想要关闭它,但我应该能够在打开连接和关闭它之间发送命令。
我对Java很陌生,我会试着在这里解释一下我想要做什么:
1)我想打开与TCP服务器的连接。 2)打开连接后,我希望能够通过调用此方法将命令发送到已打开的连接:
void sendCommand(String command) throws IOException {
out.write("c");out.flush();
out.write(command);out.flush();
}
在我完成发送命令后,我想调用一些方法来关闭我正在运行的连接。 因为我对java很新,如果有人能告诉我如何实现这个或修改我的方法,那将是非常好的。
提前谢谢你,