服务器卡在等待用户名

时间:2016-05-18 14:56:24

标签: java

我正在尝试创建一个服务器/客户端以进行聊天。我启动等待客户端连接的服务器,客户端连接,但它等待客户端发送用户名卡住了。

这是服务器:

package chat_server;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Chat_Server {
    private ServerSocket ss;
    private Socket connection;
    private List<ClientT> users;
    private static int usersNumber;

    public Chat_Server() {
        users = new ArrayList<ClientT>();
        usersNumber = 1;

        try {
            ss = new ServerSocket(2016);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println(3);
        }
    }

    public void acceptRequests() throws IOException {
        while (true) {
            try {
                connection = ss.accept();

                ClientT ct = new ClientT(connection);

                users.add(ct);

                System.out.print("Connected users: ");

                for(int i = 0; i < users.size(); i++)
                    System.out.print(users.get(i) + " ");
                System.out.println();

                ct.start();
            } catch (IOException e) {
                System.out.println("Could not accept connection from client: "
                    + e);
                System.err.println(4);
            }
        }
    }
}

    class ClientT extends Thread {
        private Socket s;
        private BufferedReader in;
        private DataOutputStream out;
        private String userName = "a";
        private String message;
        int userNr;

        public ClientT(Socket _s) {
            this.s = _s;
            userNr = usersNumber++;

            System.out.println("In client: s = " + s + " userNr = " + userNr);

            try {
                System.out.println("Creating 'in' and 'out' objects");
                out = new DataOutputStream(s.getOutputStream());
                in = new BufferedReader(new InputStreamReader(
                        s.getInputStream()));

                 System.out.println("Catching username...");

                 **//--it gets stuck here--**
                 userName = (String) in.readLine();
                System.out.println(userName + " connected...");
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println(1);
            }
         }

        public void run() {
            System.out.println("In ClientT run...");
            while (true) {
                try {
                    message = in.readLine();
                    System.out.println("Message: " + message);
                    System.out.println("Notifying all clients!");
                    messageNotifyAll(message);
                } catch (IOException e) {}
            }
        }
     }

    public static void main(String[] args) throws IOException {
        Chat_Server cs = new Chat_Server();
        System.out.println("Accepting requests...");
        cs.acceptRequests();
    }
}

这里是客户:

package chatClient;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.*;

@SuppressWarnings("serial")
public class Client extends JFrame {
    private JTextArea textArea;
    private JScrollPane scrollPane;
    private JPanel panelButtons;
    private JPanel panelList;
    private JButton send;
    private JButton disconnect;
    @SuppressWarnings("rawtypes")
    private JList userList;
    private JLabel connectedUsers;
    private JTextField text;
    private JButton sendMessage;
    private String name;
    private Socket s;
    BufferedReader in;
    DataOutputStream out;

    @SuppressWarnings("rawtypes")
    public Client(String _name) throws InterruptedException {
        System.out.println("Loading GUI...");

        //GUI left out

        System.out.println("Loading GUI finished...");

        connectToServer();
     }

    public void connectToServer() throws InterruptedException {
        try {
            textArea.append("Connecting to server...\n");
            s = new Socket("localhost", 2016);

            textArea.append("Connected to " + s.getInetAddress() + ":" +    s.getPort() +" as " + name + "...");

            in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            out = new DataOutputStream(s.getOutputStream());

            new waitForMessage().start();

            out.writeBytes(name);
        } catch (UnknownHostException e) {
            textArea.append("Server not running!");
            // e.printStackTrace();
        } catch (IOException e) {
            textArea.append(e + "\n");
            try {
                disconnectFromServer();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    public void disconnectFromServer() throws IOException {
        s.close();
        System.out.println("Disconnected!");
    }

    public class FrameExit extends WindowAdapter {
        public void windowClosing(WindowEvent e) {
            e.getWindow().dispose();
        }
    }

    public class Disconnect implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                s.close();
                System.out.println("Disconnecting...");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    public class Send implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                System.out.println("Sending message: " + text.getText());
                out.writeBytes(text.getText());
                text.setText("");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    public class waitForMessage extends Thread {
        @Override
        public void run() {
            System.out.println("Waiting for message!");
            while (true) {
                try {
                    String message = in.readLine();

                    System.out
                        .println("Message received! Displaying message in GUI!");

                    textArea.append(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
public static void main(String[] args) {
    //I have a login GUI from where I start the Client
}

}

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

服务器端似乎期望读取一行,但是没有从客户端发送的换行符。

另外,请考虑在写入后添加out.flush(),以确保实际发送数据。

out.writeBytes(name + System.getProperty("line.separator"));
out.flush();

请注意,您可以使用PrintWriter代替println方法来处理新行。

请参阅:What is the Difference between PrintWriter and DataOutputStream?