如何重新打开套接字连接?
How to reopen socket connection?
如何重新打开客户端的套接字连接,如果服务器已停止然后再次运行?
P.S。可能没必要看全部代码,看一遍Client代码中的"wait"循环
Socket socket = new Socket(ipAddress, serverPort);
while (true)
{
line = keyboard.readLine();
try
{
out.writeUTF(line);
out.flush();
line = in.readUTF();
}
catch (SocketException e)
{
while (socket.isClosed())
{
System.out.println("no signal");
try
{
Thread.sleep(200);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
//Here I need some code for reconnection
}
}
System.out.println(line);
}
如果套接字关闭连接,客户端应该在 read/write 操作中得到异常。如果客户端想要重新建立连接,只需实现它。您的 catch 块应该完全按照您在代码片段开头所做的那样创建新套接字。
类似于以下内容:
while(true) {
Socket socket = new Socket(ipAddress, serverPort);
try {
while(true) {
// read/write operations
}
} catch (SocketException e) {
continue; // this will return you to creation of new socket
}
}
如何重新打开客户端的套接字连接,如果服务器已停止然后再次运行?
P.S。可能没必要看全部代码,看一遍Client代码中的"wait"循环
Socket socket = new Socket(ipAddress, serverPort);
while (true)
{
line = keyboard.readLine();
try
{
out.writeUTF(line);
out.flush();
line = in.readUTF();
}
catch (SocketException e)
{
while (socket.isClosed())
{
System.out.println("no signal");
try
{
Thread.sleep(200);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
//Here I need some code for reconnection
}
}
System.out.println(line);
}
如果套接字关闭连接,客户端应该在 read/write 操作中得到异常。如果客户端想要重新建立连接,只需实现它。您的 catch 块应该完全按照您在代码片段开头所做的那样创建新套接字。
类似于以下内容:
while(true) {
Socket socket = new Socket(ipAddress, serverPort);
try {
while(true) {
// read/write operations
}
} catch (SocketException e) {
continue; // this will return you to creation of new socket
}
}