Results 1 to 2 of 2
  1. #1
    bemol is offline Member
    Join Date
    Jan 2014
    Posts
    1
    Rep Power
    0

    Default Possible deadlock

    Hello.
    Using this guide: javanetexamples, I tried to create an application that works on sockets. More precisely chat.
    I created 5 classes:
    ChatClient - is responsible for GUI and communicate with the server
    CommunicationServer - server creates a ServerSocket and listens to new clients
    CommunicationServerConsole - windowed application - server console (redirects System.out on textArea of the JPanel)
    TextAreaPrintStream - class, which allows me to write in the textArea content that is printed on the console
    CommunicationHandler - class is responsible for initialization and communication with the client

    Unfortunately, there was a problem: the application hangs on the line, who is trying to write text to the client OutputStream (line: out.println("$nick"); in CommunicationHandler.java). It does not show any message or exception
    I exlude imports, getters, setters from sources and TextAreaPrintStream class.
    The main class of the server is CommunicationServerConsole; of the client is ChatClient

    Java Code:
    @SuppressWarnings("serial")
    public class CommunicationServerConsole extends JPanel {
     
        private JTextArea textArea = new JTextArea(15, 30);
        private TextAreaPrintStream taps = new TextAreaPrintStream(
                textArea, "Server");
     
        public CommunicationServerConsole() {
            setLayout(new BorderLayout());
            add(new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
            System.setOut(taps);
            textArea.setEnabled(false);
            textArea.setFont(new Font("Arial Unicode MS", Font.PLAIN, 12));
            textArea.setBackground(Color.BLACK);
        }
     
        private static void init() {
            JFrame frame = new JFrame("Communication Server Console");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new CommunicationServerConsole());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
     
        public static void main(String[] args) {
     
            init();
            CommunicationServer.getInstance();
        }
    }
    Java Code:
    final public class CommunicationServer {
     
        private static volatile CommunicationServer instance = null;
        private static final int PORT = 9001;
        private HashMap<String, PrintWriter> clients = new LinkedHashMap<String, PrintWriter>();
     
        private CommunicationServer() {
            try {
                System.out.println("Initializing server chat...");
                createServer();
            } catch (IOException ex) {
                Logger.getLogger(CommunicationServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
     
        public static CommunicationServer getInstance() {
            if (instance == null) {
                synchronized (CommunicationServer.class) {
                    if (instance == null) {
                        instance = new CommunicationServer();
                    }
                }
            }
            return instance;
        }
     
        public void createServer() throws IOException {
            ServerSocket serverSocket = new ServerSocket(PORT);
            System.out.println("Server was created successfully.");
            try {
                while (true) {
                    new CommunicationHandler(serverSocket.accept()).start();
                }
            } finally {
                serverSocket.close();
            }
        }
    }
    Java Code:
    public class CommunicationHandler extends Thread {
     
        private String nick;
        private Socket socket;
        private BufferedReader in;
        private PrintWriter out;
     
        public CommunicationHandler(Socket socket) {
            super();
            this.socket = socket;
        }
     
        @Override
        public void run() {
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream());
     
                createNickname();
                listening();
     
            } catch (IOException ex) {
                Logger.getLogger(CommunicationHandler.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                if (nick != null) {
                    CommunicationServer.getInstance().getClients().remove(nick);
                }
                try {
                    socket.close();
                } catch (IOException ex) {
                    Logger.getLogger(CommunicationHandler.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
     
        private void createNickname() throws IOException {
            while (true) {
                out.println("$nick");
                nick = in.readLine();
                if (nick == null || "".equals(nick)) {
                    return;
                }
                synchronized (CommunicationServer.getInstance().getClients()) {
                    if (!CommunicationServer.getInstance().getClients().containsKey(nick)) {
                        CommunicationServer.getInstance().getClients().put(nick, out);
                        out.println("$nickaccepted");
                        break;
                    } else {
                        out.println("Nickname is occupied.");
                    }
                }
            }
        }
     
        private void listening() throws IOException {
            while (true) {
                String input = in.readLine();
                if (input == null || "".equals(input)) {
                    return;
                }
                for (PrintWriter writer : CommunicationServer.getInstance().getClients().values()) {
                    writer.println("MSG " + nick + ": " + input);
                }
            }
        }
    }
    Java Code:
    public class ChatClient {
     
        private Boolean isConnected = false;
        private BufferedReader in;
        private PrintWriter out;
        private JFrame frame = new JFrame("Chat");
        private JTextField textField = new JTextField(40);
        private JTextArea messageArea = new JTextArea(8, 40);
     
        public ChatClient() {
            textField.setEditable(false);
            messageArea.setEditable(false);
            frame.getContentPane().add(textField, "North");
            frame.getContentPane().add(new JScrollPane(messageArea), "Center");
            frame.pack();
     
            textField.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    out.println(textField.getText());
                    textField.setText("");
                }
            });
        }
     
        private String getServerAddress() {
            return JOptionPane.showInputDialog(
                    frame,
                    "Enter IP Address of the Server:",
                    "Welcome to the chat",
                    JOptionPane.QUESTION_MESSAGE);
        }
     
        private String getName() {
            return JOptionPane.showInputDialog(
                    frame,
                    "Choose a screen name:",
                    "Screen name selection",
                    JOptionPane.PLAIN_MESSAGE);
        }
     
        private void connectToServer() throws UnknownHostException, IOException {
            String serverAddress = getServerAddress();
            Socket socket = new Socket(serverAddress, 9001);
            in = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            isConnected = true;
        }
     
        private void run() {
     
            do {
                try {
     
                    connectToServer();
     
                    while (true) {
                        String line = in.readLine();
                        if (line.startsWith("$nick")) {
                            out.println(getName());
                        } else if (line.startsWith("$nickaccepted")) {
                            textField.setEditable(true);
                        } else if (line.startsWith("MSG")) {
                            messageArea.append(line.substring(8) + "\n");
                        }
                    }
                } catch (ConnectException | UnknownHostException e) {
                    Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, "Nie odnaleziono hosta.");
                } catch (IOException e) {
                    Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, "Błąd połączenia.");
                }
            } while (!isConnected);
        }
     
        public static void main(String[] args) throws Exception {
            ChatClient client = new ChatClient();
            client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            client.frame.setVisible(true);
            client.run();
        }
    }
    Please help.

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: Possible deadlock

    No. It is probably hanging on the NEXT line (the readline) as that is a blocking operation waiting on a response from the other end that is probably still waiting on your "$nick" message as you are not flushing the PrintWriter and the message you wish to send is probably still sitting in the buffer. Sending a newline (of the form \r\n for network communications) right after "$nick" wouldn't hurt, either.

    Also, you DO know that a PrintWriter will silently swallow errors, right? Is that really what you want?

Similar Threads

  1. Deadlock with DocumentListener
    By dsharma in forum AWT / Swing
    Replies: 6
    Last Post: 04-30-2012, 03:30 PM
  2. Compiler deadlock
    By Arnold in forum New To Java
    Replies: 2
    Last Post: 06-27-2010, 12:57 PM
  3. How to avoid the Deadlock in the below program
    By murali1253 in forum New To Java
    Replies: 3
    Last Post: 04-16-2010, 05:46 PM
  4. [SOLVED] Deadlock ?
    By jon80 in forum New To Java
    Replies: 1
    Last Post: 06-14-2009, 07:54 PM
  5. Thread Deadlock
    By ajeeb in forum New To Java
    Replies: 2
    Last Post: 01-16-2009, 02:49 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •