【发布时间】:2015-05-15 02:39:40
【问题描述】:
我有一个服务器,它在客户端连接时接受套接字。我希望能够关闭我的本地服务器并让我的客户端尝试重新连接大约 5 次,如果我启动我的服务器,客户端应该会指示您已重新连接。
我有点理解这是在try{} catch(IOException){Here goes the code for handleing reconnect} 中完成的,我想使用我第一次连接时使用的同一个套接字。我不想创建new Client,因为我必须重新输入用户名之类的东西
我尝试创建一个像clientSocket = new Socket("localhost", portnr) 这样的新套接字,但我不知道这是否是正确的方法。如果您有可以回答此问题的示例,请链接它们。我不介意阅读,只要它有良好的文档记录。提前致谢!
编辑。 这是我的客户类
public class Client {
public static void main(String[] args) {
Client client = new Client();
client.connect();
}
//------------------------------------------------------------
//METHOD CONNECT
//------------------------------------------------------------
private void connect(){
int reConnectTries = 0;
Socket clientsocket;
try {
//------------------------------------------------
//Sets up variables needded for execution
clientsocket = new Socket("localhost", 8900);
DataOutputStream OUT = new DataOutputStream(clientsocket.getOutputStream());
ListenforMessages listen = new ListenforMessages(clientsocket);
//We don't want to enter username all the time
//So this goes not in the while-loop
//------------------------------------------------
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter username");
String username = keyboard.nextLine();
//Sends username to sever so it can be added to a list
OUT.writeUTF(username);
//------------------------------------------------
//------------------------------
//Creates a thread to listen on messages from server(Other clients in this case)
Thread trd = new Thread(listen);
trd.start();
//------------------------------
while (true) {
try {
String sendMessage = keyboard.nextLine();
OUT.writeUTF(sendMessage);
OUT.flush();
} catch (Exception e) {
System.err.println("Could not send message to server. " + e);
}
}
} catch (IOException e) {
System.err.println("Couldnt establish a connection: " + e);
}
}
//------------------------------------------------------------
//CLASS FOR HANDLEING INPUT. We create a class for input on a new thread
//This is cause we don't want it to block other processes.
//----------------------------------------------------------------
class ListenforMessages implements Runnable{
Socket mySocket;
DataInputStream IN;
public ListenforMessages(Socket X) throws IOException {
this.mySocket = X;
}
@Override
public void run() {
try {
IN = new DataInputStream(mySocket.getInputStream());
while (true) {
System.out.println(IN.readUTF());
}
} catch (Exception e) {
System.err.println("Couldn't fetch message from server.Error: " + e);
}
}
}
}
【问题讨论】:
-
1.相同的 Socket:所以在您的客户端中,使用 null 构造函数创建一个 Socket,并使用
connect方法连接到服务器。然后,如果您断开连接,您可以再次使用connect。 2. 用户登录数据一次:在客户端捕获此信息,并在连接后以编程方式将其登录到服务器 -
你的意思是
Socket clientSocket = new Socket()然后是clientSocket.connect("localhost", portnr)?我将如何使用 connect 重新连接? -
我不明白 Bojje 的问题。您使用与第一次连接相同的方式进行操作
-
要我添加代码,希望这样更有意义吗?
-
哦,现在我明白你的意思了。看到我想要的是我必须自己实现的东西。我的问题是我的客户使用用户名被接受,没问题。但问题是我希望客户端使用相同的名称进行连接。
标签: java sockets client server reconnect