如何循环回初始运行功能

时间:2017-01-29 09:12:42

标签: java loops networking server client

晚上好,我对Java网络很陌生,我正在创建一个服务器和客户端。在客户端上,我想在response()方法中获得响应之后循环回run()方法,但是我不确定如何实现它。我最初的想法是这样的:但它不起作用。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client implements Runnable
{
public Client()
{
    try
    {
        socket = new Socket(IP, PORT);
        writer = new PrintWriter(socket.getOutputStream());
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        running = true;

        runningThread = new Thread(this);
        runningThread.start();
    }catch(Exception e){e.printStackTrace(); disconnect();}
}

public void disconnect()
{
    running = false;
    if(runningThread != null)
        runningThread.interrupt();
    runningThread = null;

    try
    {
        reader.close();
    }catch(Exception e){}
    reader = null;

    try
    {
        writer.close();
    }catch(Exception e){}
    writer = null;
    try
    {
        socket.close();
    }catch(Exception e){}
    socket = null;
}

public void sendMessage(String message)
{
    if(running)
    {
        writer.println(message);
        writer.flush();
    }
}

public void response()
{
    try
    {

        String response = "";
        while((response = reader.readLine()) != null && running)
        {
            System.out.println("Recieved Response '" + response + "'");
            run();
        }
    }catch(Exception e) {disconnect();}
}

public void run()
{
    try
    {
        Scanner scan = new Scanner(System.in);
        String message = "";
        while((message = reader.readLine()) != null && running)
        {
            System.out.println(message);

            System.out.println("Enter Command: ");
            String command = scan.nextLine();

            sendMessage(command);
            command = "";
            scan.close();
            response();
        }
    }catch(Exception e){disconnect();}

    }

private Socket socket;
private PrintWriter writer;
private BufferedReader reader;

private Thread runningThread;
private boolean running;

private static final int PORT = ----;
private static final String IP = "--------";

public static void main(String args[])
{
    new Client();
}
}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试将disconnect方法放入finally块或try catch块中。

e.g。

} catch(Exception e) {
  // error ignored
} finally {
  disconnect();
}

更多信息,请参阅here