Results 1 to 8 of 8
  1. #1
    eLancaster is offline Member
    Join Date
    Jan 2011
    Posts
    93
    Rep Power
    0

    Default Messages not received by chat client.

    I've written code for a chat server and a chat client.
    The chat server sends messages from one chat client to all participating clients.
    According to logs, message gets sent.
    The receiving thread on the client doesn't receive them though.

    Code's below:
    ChatClient.java
    Java Code:
    public class ChatClient {
    	
    	private JTextArea receivedMessagesArea;
    	private JTextField outgoingMessageField;
    	private JButton sendButton;
    	private JLabel statusLabel;
    	
    	private BufferedReader readFromServer;
    	private PrintWriter writeToServer;
    	
    	private Socket chatServer;
    	private String name;
    
    	
    	public ChatClient()
    	{
    		//set up ui and call ConnectToServer.
    		//action listener of sendbutton will send message to server. Text will also be appended to receivedMessagesArea
    		this.name = JOptionPane.showInputDialog(null, "Enter your name", "Login Name", JOptionPane.OK_OPTION);
    		
    		JFrame frame = new JFrame();
    		JPanel panel = new JPanel();
    		panel.setLayout(null);
    		
    		receivedMessagesArea = new JTextArea(15,50);
    		receivedMessagesArea.setText("");
    		receivedMessagesArea.setLineWrap(true);
    		receivedMessagesArea.setWrapStyleWord(true);
    		receivedMessagesArea.setEditable(false);
    		this.receivedMessagesArea.setBounds(10, 10, 440, 365);
    		
    		JScrollPane scroller = new JScrollPane(this.receivedMessagesArea);
    		scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    		
    		panel.add(this.receivedMessagesArea);
    		
    		
    		panel.add(scroller);
    		
    		outgoingMessageField = new JTextField("Enter Message Here");
    		this.outgoingMessageField.setEditable(true);
    		this.outgoingMessageField.requestFocus(true);
    		this.outgoingMessageField.setBounds(10,380,340,20);
    		panel.add(this.outgoingMessageField);
    		
    		sendButton = new JButton("Send");
    		this.sendButton.setBounds(359,380,90,20);
    		this.sendButton.setActionCommand("Send");
    		this.sendButton.addActionListener(
    				new ActionListener()
    				{
    					public void actionPerformed(ActionEvent event)
    					{
    						if(sendButton.getActionCommand().equals("Send"))
    						{
    							System.out.printf("Log: ActionCommand: %s\n", sendButton.getActionCommand());
    							if(updateConnectionStatus()==true)
    							{
    								try{
    									writeToServer.printf("%s: %s\n",name,outgoingMessageField.getText());
    									writeToServer.flush();
    								
    									//receivedMessagesArea.append(String.format("%s: %s\n", "Me",outgoingMessageField.getText()));
    									
    									System.out.printf("Log: Message sent to %s : \"%s\" \n",chatServer.getLocalSocketAddress(),outgoingMessageField.getText());
    									outgoingMessageField.setText("");
    									outgoingMessageField.requestFocus(true);
    									
    								}catch(Exception e)
    								{
    									System.out.println("Log: Exception sending Message");
    								}
    							}	
    						}
    							
    						if(sendButton.getActionCommand().equals("Connect"))
    						{
    							System.out.printf("Log: ActionCommand: %s\n", sendButton.getActionCommand());
    							connectToServer();
    						}
    					}
    				}
    		);
    		panel.add(this.sendButton);
    		
    		statusLabel = new JLabel("");
    		statusLabel.setBounds(106,403,200,15);
    		panel.add(this.statusLabel);
    				
    		this.connectToServer();
    		
    		Thread receiveMessages = new Thread(new Messenger());
    		receiveMessages.setName("Message Receiving Thread");
    		receiveMessages.start();
    	
    		frame.setTitle(String.format("Messenger v1.0 Build 1 | %s",this.name));
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.getContentPane().add(BorderLayout.CENTER, panel);
    		frame.setSize(475, 455);
    		frame.setVisible(true);
    		
    	}
    	
    	private void connectToServer()
    	{
    		
    		
    		System.out.print("Log: Connecting to server\n");
    		try{
    			chatServer = new Socket("127.0.0.1",8558);
    			readFromServer = new BufferedReader( new InputStreamReader(this.chatServer.getInputStream()));
    			writeToServer = new PrintWriter(this.chatServer.getOutputStream());
    			updateConnectionStatus();
    		}catch(Exception e)
    		{
    			this.statusLabel.setText("Connection Failed.");
    			System.out.printf("Log: Failed to connect with Server.\n");
    		}
    	}
    	
    	private boolean updateConnectionStatus()
    	{
    		try{
    			System.out.printf("Log: Connection with %s persists.\n", this.chatServer.getLocalSocketAddress());
    			this.sendButton.setText("Send");
    			this.sendButton.setActionCommand("Send");
    			this.outgoingMessageField.setEnabled(true);
    			this.statusLabel.setText("Connection Established.");
    			return true;
    		}catch(Exception e)
    		{
    			System.out.print("Log: Connection to Server failed.\n");
    			this.sendButton.setText("Connect");
    			this.sendButton.setActionCommand("Connect");
    			this.outgoingMessageField.setEnabled(false);
    			this.statusLabel.setText("Connection Failed");
    			return false;
    		}
    	}
    	
    	public static void main(String args[])
    	{
    		new ChatClient();
    	}
    	
    	class Messenger implements Runnable
    	{
    		public void run()
    		{
    			System.out.printf("Log: %s has started running.\n",Thread.currentThread().getName());
    			String receivedMessage;
    			try{
    				while((receivedMessage = readFromServer.readLine())!=null)
    				{
    					System.out.printf("Log: Message received from Server: \"%s\"\n", receivedMessage);
    					receivedMessagesArea.append(receivedMessage);
    				}
    			}catch(Exception e)
    			{
    				System.out.println("Log: Exception thrown while reading from server.");
    			}
    			System.out.printf("Log: %s is dead.\n",Thread.currentThread().getName());
    		}
    	}
    }
    ChatServer.java
    Java Code:
    public class ChatServer {
    	private ArrayList<PrintWriter> clientsList;
    	
    	public ChatServer()
    	{
    		try
    		{
    			//make the server
    			ServerSocket chatServer = new ServerSocket(8558);
    			System.out.printf("Server Running at %s\n", chatServer.getLocalSocketAddress());
    			
    			clientsList = new ArrayList<PrintWriter>();
    			while(true)
    			{
    				Socket client = chatServer.accept();
    				PrintWriter writer = new PrintWriter(client.getOutputStream());
    				clientsList.add(writer);
    				
    				Thread receiver = new Thread(new Deliverer(client));
    				receiver.setName("Message Receiving Thread");
    				receiver.start();
    				
    				System.out.printf("Log: Client %s has connected to Server.\n", client.getLocalSocketAddress());
    				
    			}
    		}catch(Exception e)
    		{
    			System.out.print("Log: Error Establishing Server\n");
    		}
    		
    	}
    	
    	private void sendToParticipants(String message)
    	{
    		int participant =0;
    		Iterator clientWritersListIterator = clientsList.iterator();
    		
    		if(clientWritersListIterator.hasNext()==false)
    		{
    			System.out.println("Log: There are no participants in this Chat. Message can not be sent.");
    		}
    		while(clientWritersListIterator.hasNext())
    		{
    			try{
    				PrintWriter writeToClients = (PrintWriter) clientWritersListIterator.next();
    				writeToClients.println(message);
    				System.out.printf("Log: Message sent to participants : \" %s \".\n", message);
    			}catch(Exception e)
    			{
    				System.out.println("Log: Exception thrown while sending message to clients");
    			}
    		}
    	}
    	
    	class Deliverer implements Runnable
    	{
    		BufferedReader reader;
    		
    		public Deliverer(Socket client)
    		{
    			System.out.printf("Log: %s has started running.\n",Thread.currentThread().getName());
    			try{
    				reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    			}catch(IOException e)
    			{
    				System.out.println("Log: Exception thrown while reading message from client.");
    			}
    		}
    		
    		public void run()
    		{
    			String message;
    			try{
    				while((message = reader.readLine())!=null)
    				{
    					System.out.printf("Log: Message received : %s\n", message);
    					sendToParticipants(message);
    				}
    			}catch(Exception e)
    			{
    				System.out.println("Log: Message could not be read");
    			}
    		}
    	}
    	
    	public static void main(String args[])
    	{
    		new ChatServer();
    	}
    }
    Thanks for the time.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    Why does the server side code receive the messages and the client side doesn't?
    What is different between those two communications? The client sends ok. The server doesn't.
    Look at the code.

  3. #3
    eLancaster is offline Member
    Join Date
    Jan 2011
    Posts
    93
    Rep Power
    0

    Default

    Oh I see, forgot to flush! ;P

    Thanks Norm.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    Great. You got it.
    When one part works and another doesn't, that should raise the question: why, what is different.

  5. #5
    Joel's Avatar
    Joel is offline Member
    Join Date
    May 2011
    Location
    Placerville, CA
    Posts
    86
    Rep Power
    0

    Default

    wow, great program! Network programming is definitely the funnest part of Java after GUI development...

  6. #6
    eLancaster is offline Member
    Join Date
    Jan 2011
    Posts
    93
    Rep Power
    0

    Default

    Thanks! (Although I'm not so sure what's so great about it. Seems quite ordinary).
    Same thoughts here - It's incredibly simple and powerful :D. Wish it was like that for C++.
    Last edited by eLancaster; 06-21-2011 at 10:37 PM.

  7. #7
    Joel's Avatar
    Joel is offline Member
    Join Date
    May 2011
    Location
    Placerville, CA
    Posts
    86
    Rep Power
    0

    Default

    I remember C++ took an awful lot of tinkering for it to run client-server applications, even anything remotely like Swing. I am actually only at an intermediate level and just starting to dabble into Java networking programs...

  8. #8
    Joel's Avatar
    Joel is offline Member
    Join Date
    May 2011
    Location
    Placerville, CA
    Posts
    86
    Rep Power
    0

    Default

    so every time I learn some new implementation of Java it is exciting. I am actually in the middle of programming a Spanish-language teaching software application with Java...

Similar Threads

  1. Two-way chat, how can I be able to send messages?
    By Vortexnl in forum New To Java
    Replies: 4
    Last Post: 02-05-2011, 10:21 PM
  2. can't send messages correctly [chat]
    By michail in forum New To Java
    Replies: 1
    Last Post: 05-11-2010, 11:24 AM
  3. Replies: 7
    Last Post: 03-28-2009, 07:20 PM
  4. client/server messages exchange after 5 min
    By dim_ath in forum Advanced Java
    Replies: 2
    Last Post: 01-22-2008, 09:46 AM
  5. Replies: 3
    Last Post: 01-07-2008, 08:01 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
  •