Java 根据请求保持客户端到服务器连接打开和关闭
我有一个Java中的TCP客户端应用程序,通过这个应用程序我可以与服务器应用程序通信 我有一个简单的方法sendCommand,它将消息发送到服务器:Java 根据请求保持客户端到服务器连接打开和关闭,java,Java,我有一个Java中的TCP客户端应用程序,通过这个应用程序我可以与服务器应用程序通信 我有一个简单的方法sendCommand,它将消息发送到服务器: void sendCommand(String command) throws IOException { String ipaddress = "192.168.0.2"; Socket commandSocket = null; PrintWriter out = null; BufferedWriter out = nul
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非常陌生,如果有人能告诉我如何实现或修改我的方法,那将非常好
提前谢谢你,但是。。。为什么你需要线程呢?您不能打开连接,发送命令,然后关闭连接吗?我如何打开连接,现在单击按钮并发送命令,在2分钟内单击按钮并向现有连接发送命令,然后在以后的任何时间单击该按钮并发送另一个命令,完成后,单击一个按钮并关闭连接。