Java Socket编程:客户端收到“”而不是id

时间:2018-02-08 09:13:09

标签: java sockets bufferedreader printwriter

我正在使用套接字编写一个简单的聊天程序。该程序在客户端连接到服务器时工作,在开始聊天之前,他们将其名称发送到服务器并在返回时接收唯一ID。这是我的代码无法正常工作的地方。

这是Client类中的代码,它发送名称并接收id:

private void exchangeInformation() {
        String temp;
        try {
            writer.println(name);
            temp = reader.readLine();
            System.out.println(temp);
            temp = reader.readLine();
            System.out.println("id has been received : "
                    + temp);
            this.id = Integer.parseInt(temp);

        } catch (IOException e) {
            System.out.println("Error Occured\n"
                    + "Message: Couldn't get id from server\n"
                    + "Cause: " + e.getMessage() + "\n");
        }
    }

这是服务器端的代码,它接收名称并发送id:

private void exchangeInformation() {

        try {
            String n = reader.readLine();
            setUserName(n);
            System.out.println("name has been received");
            writeMessage("Server: Welcome " + userName + "\n");

            writeMessage(userId);
        } catch (IOException e) {
            System.out.println("Error Occured\n"
                    + "Message: Couldn't receive client's name\n"
                    + "Cause: " + e.getMessage() + "\n");
        }
    }

这是服务器端的writeMessage方法:

public synchronized void writeMessage(String message) {
        writer.println(message);
    }

在双方中,writerPrintWriter的对象,而readerBufferedReader的对象。

嗯,问题是,当我向客户端发送userId时,客户端会收到“”而不是正确的数据。代码的其他部分工作正常。

问题是什么,我该如何解决?

此致

编辑:正如评论中所建议的,所有代码:

Client上课:

public class Client {

    private String name;
    private int id;
    private boolean isConnected;

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

    public Client(String name) {
        this.name = name;
    }

    public boolean getIsConnected() {
        return isConnected;
    }

    public BufferedReader getReader() {
        return reader;
    }

    public void start() {

        connect();

        exchangeInformation();

        new ReceiveFromServer(this).start();

        String output;
        Scanner in = new Scanner(System.in);
        while (isConnected) {
            System.out.println("YOU: ");
            output = in.nextLine();
            writer.print(name + " : " + output);
        }

        try {
            socket.close();
            reader.close();
            writer.close();
        } catch (IOException e) {
            System.out.println("Error Occured\n"
                    + "Message: Couldn't close content(s)\n"
                    + "Cause: " + e.getMessage() + "\n");
        }
    }

    private void connect() {
        System.out.println("Trying to connect to the server...\n");
        try {
            socket = new Socket("localhost", 4444);
        } catch (IOException e) {
            System.out.println("Error Occured\n"
                    + "Message: User " + name + " couldn't connetct to the server\n"
                    + "Cause: " + e.getMessage() + "\n");
        }
        try {
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new PrintWriter(socket.getOutputStream(), true);
        } catch (IOException e) {
            System.out.println("Error Occured\n"
                    + "Message: Couldn't get socket's InputStream or OutputStream\n"
                    + "Cause: " + e.getMessage());
        }

        System.out.println("You have cnnected to the server successfully");
    }

    private void exchangeInformation() {
        String temp;
        try {
            writer.println(name);
            temp = reader.readLine();
            System.out.println(temp);
            temp = reader.readLine();
            System.out.println("id has been received : "
                    + temp);
            this.id = Integer.parseInt(temp);

        } catch (IOException e) {
            System.out.println("Error Occured\n"
                    + "Message: Couldn't get id from server\n"
                    + "Cause: " + e.getMessage() + "\n");
        }
    }

}

Server上课:

public class Server {

    private static Server server = new Server(4444);

    private final int PORT;
    private List<ClientThread> clients;
    private static int counter;

    private ServerSocket ss;
    private boolean isListening;

    private Server(int port) {
        this.PORT = port;
        clients = new ArrayList<>();
        counter = 0;
    }

    public static Server getServerInstance() {
        return server;
    }

    private int generateId() {
        return ++counter;
    }

    public void start() {
        establishConnection();

        while (isListening) {
            System.out.println("Server is Listening...");
            Socket s = null;
            try {
                s = ss.accept();
            } catch (IOException e) {
                System.out.println("Error Occured\n"
                        + "Message: An error occured while accepting a request\n"
                        + "Cause: " + e.getMessage());
            }
            System.out.println("New connection request has been accepted\n");
            ClientThread client = new ClientThread(s, this.generateId());
            clients.add(client);
            client.start();
        }

        try {
            ss.close();
        } catch (IOException e) {
            System.out.println("Error Occured\n"
                    + "Message: Couldn't close Server Socket\n"
                    + "Cause: " + e.getMessage() + "\n");
        }

    }

    public static synchronized void broadcastMessage(String message) {
        Server s = getServerInstance();
        for (int i = 0; i < s.clients.size(); i++) {
            s.clients.get(i).writeMessage(message);
        }
    }

    private void establishConnection() {
        try {
            ss = new ServerSocket(4444);
        } catch (IOException e) {
            System.out.println("Error Occured\n"
                    + "Message: Couldn't establish server socket for connection\n"
                    + "Cause: " + e.getMessage() + "\n");
        }
        System.out.println("Server Socket has been created Successfully\n");
        isListening = true;
    }

    public static void removeClient(int id) {
        Server s = getServerInstance();
        for (int i = 0; i < s.clients.size(); i++) {
            if (id == s.clients.get(i).getId()) {
                s.clients.remove(i);
                break;
            }
        }
    }

}

ClientThread上课:

public class ClientThread extends Thread {

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

    private int userId;
    private String userName;

    private boolean isConnected;

    public ClientThread(Socket socket, int id) {
        this.socket = socket;

        try {
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new PrintWriter(socket.getOutputStream(), true);
        } catch (IOException e) {
            System.out.println("Error Occured\n"
                    + "Message: Couldn't get socket's InputStream or OutputStream\n"
                    + "Cause: " + e.getMessage());
        }

        this.userId = id;

    }

    public void setUserName(String name) {
        this.userName = name;
    }

    public void setIsConnected(boolean flag) {
        isConnected = flag;
    }

    public BufferedReader getReader() {
        return reader;
    }

    public int getUserId() {
        return userId;
    }

    @Override
    public void run() {

        exchangeInformation();

        isConnected = true;
        String input;
        while (isConnected) {
            try {
                input = reader.readLine();
                if (input != null) {
                    if (input.equalsIgnoreCase("logout")) {
                        logout();
                    } else {
                        Server.broadcastMessage(input);
                    }
                }
            } catch (IOException e) {
                System.out.println("Error Occured\n"
                        + "Message: Couldn't receive message from client\n"
                        + "Cause: " + e.getMessage() + "\n");
                isConnected = false;
            }

        }
    }

    public synchronized void writeMessage(String message) {
        writer.println(message);
    }

    public void writeMessage(int message) {
        writer.println(message);
    }

    private void logout() {
        setIsConnected(false);

        try {
            socket.close();
            reader.close();
            writer.close();
            System.out.println("User " + this.userId + " has loggedout"
            );
        } catch (IOException e) {
            System.out.println("Error Occured\n"
                    + "Message: Couldn't close content(s)\n"
                    + "Cause: " + e.getMessage() + "\n");
        }
    }

    private void exchangeInformation() {

        try {
            String n = reader.readLine();
            setUserName(n);
            System.out.println("name has been received");
            writeMessage("Server: Welcome " + userName + "\n");

            writeMessage(userId);
        } catch (IOException e) {
            System.out.println("Error Occured\n"
                    + "Message: Couldn't receive client's name\n"
                    + "Cause: " + e.getMessage() + "\n");
        }
    }
}

0 个答案:

没有答案