如何在不关闭服务器套接字的情况下在客户端获得确认?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在不关闭服务器套接字的情况下在客户端获得确认?相关的知识,希望对你有一定的参考价值。
我能够将字符串发送到服务器,服务器也收到相同的信息。服务器能够发送确认,但客户端在服务器结束连接之前未得到确认。但我不想关闭连接。如何在不关闭连接的情况下显示确认?
//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();
}
}
}
答案
如何在不关闭连接的情况下显示确认?
在您的客户端,您正在做一个阅读线:
String message = br.readLine();
但是,从服务器,您没有发送完整的行。您需要在邮件末尾添加行终止字符:
ack = "Ok
";
bw.write(ack);
然后读取线完成,客户端获得确认。显然错误确认也需要换行符("Error
"
)。
确保正确关闭在Socket4.run()
中创建的已接受套接字和服务器套接字。我假设您只是发布部分代码但确保在try / finally块中关闭这些套接字。
以上是关于如何在不关闭服务器套接字的情况下在客户端获得确认?的主要内容,如果未能解决你的问题,请参考以下文章
如何在不安装任何数据库服务器的情况下在本地运行带有数据库的桌面应用程序?
我能否在不依赖客户从 PayPal 中单击“返回站点”的情况下从 PayPal Standard 获得订单确认?