我能够将字符串发送到服务器,服务器也收到了相同的信息。服务器能够发送确认,但客户端在服务器结束连接之前未得到确认。但我不想关闭连接。如何在不关闭连接的情况下显示确认?
//This is Client
public void Actuator1_Stop(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Socket socket = new Socket("localhost", 1028);
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
dout.writeUTF("Stop_Actuator");
dout.flush();
System.out.println("Command Sent = Stop_Actuator");
//Get the return message from server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("ACK received from the server : " +message);
socket.close();
} catch(Exception exception) {
exception.printStackTrace();
}
}
//This is Server
class Socket4 implements Runnable {
public void run() {
try {
ServerSocket ss = new ServerSocket(1028);
while(true) {
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String cmd = dis.readUTF();
System.out.println("Command= "+cmd);
//Sending the response back to the client
String ack = null;
OutputStream os = s.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
if(cmd.equals("Stop_Actuator")) {
ack= "Ok";
bw.write(ack);
} else {
ack = "Error";
bw.write(ack);
}
System.out.println("ACK sent to the client is "+ack);
bw.flush();
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
public class MyServer {
public static void main(String[] args) {
Socket1 s1 = new Socket1();
Socket2 s2 = new Socket2();
Socket3 s3 = new Socket3();
Socket4 s4 = new Socket4();
Thread t1 = new Thread(s1);
Thread t2 = new Thread(s2);
Thread t3 = new Thread(s3);
Thread t4 = new Thread(s4);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
}
答案 0 :(得分:0)
如何在不关闭连接的情况下显示确认?
在您的客户端,您正在阅读:
String message = br.readLine();
然而,从服务器您没有发送完整的行。您需要在邮件末尾添加行终止字符:
ack = "Ok\n";
bw.write(ack);
然后读取线完成,客户端获得确认。显然错误确认也需要换行符("Error\n"
)。
确保正确关闭在Socket4.run()
中创建的已接受套接字和服务器套接字。我假设您只是发布部分代码,但请确保在try / finally块中关闭这些套接字。