5 Replies - 40655 Views - Last Post: 30 April 2012 - 05:37 PM Rate Topic: -----

#1 Saya_26  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 40
  • Joined: 07-November 11

Chat using sockets(Single server with multiple clients)

Posted 30 April 2012 - 03:36 PM

Hi,

I am programming a chat application using sockets. The main protocol is that when you run the program, it will first ask your user name. It will keep a record of the names entered. And after the name is submitted, it will show you the chat interface (not good with GUI, so I need to improve on that). The input Field will now allow you to type messages and broadcasts them. My problem, in simple words, is that it doesn't work. JOptionPane doesn't work so the input Field is not editable. I don't know what I am doing wrong. I would appreciate any help!.. though in simple words please, I am still at a beginner level.

Here is the code for the Server.

package chatappserver;

import java.net.*;
import java.io.*;
import java.util.Vector;
import java.lang.*;

public class ChatappServer {
    
    private static int port = 1234;
    private static ServerSocket server = null;
    private static Socket clientSocket;
    private static String line;
    private static BufferedReader streamIn;
    private static PrintStream streamOut;
    
    
    private static Vector<String> usernames = new Vector<String>();
    private static Vector<PrintStream> streams = new Vector<PrintStream>();
    
    public static void main(String[] args) throws IOException{
        
        try{
            System.out.println("Connecting to port " + port + " ....");
            server = new ServerSocket(port);
            System.out.println("Chat application server is now running..");
            while(true){
            clientSocket = server.accept();
            chatHandler c = new chatHandler(clientSocket);
            c.start();
            }
        }
        catch(IOException e){
            System.out.println("Couldn't connect to the port!");
        }
        finally{
            server.close();
        }       
    }
    
    private static class chatHandler extends Thread{
        
        private Socket clientSocket;
        
        public chatHandler(Socket clientSocket){            
            super("chatHandler");
            this.clientSocket = clientSocket;
        }
        
        public void run(){
           
            try{
              streamIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
              streamOut = new PrintStream(clientSocket.getOutputStream(), true);
            
              while(true){
                streamOut.println("Username");
                String line = streamIn.readLine();
                if (line == null){
                    return;            
                }
                try{
                    synchronized(usernames){
                        if(!usernames.contains(line)){
                            usernames.add(line);
                            break;
                        }
                    }
                }
                catch(Exception e){
                    System.out.println(e);
                }                
              }
              streamOut.println("Welcome");
              streams.add(streamOut);
              
              while(true){
              String message = streamIn.readLine();
              if(message == null){
                  return;
              }
              for(PrintStream stream : streams){
                  stream.println("From " + line + ": " + message);
              }
              
            }
            }
            catch(IOException e){
                System.out.println(e);
                
            }
            finally{
                if(line != null && streamOut != null){
                    usernames.remove(line);
                    streams.remove(streamOut);
                }
                try{
                    clientSocket.close();
                }
                catch(IOException e){
                    System.out.println(e);
                }
                
            }
            
                
            }
            
            
        }
        
    }






The Client code is here..

package chatappclient;

import java.net.*;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.*;
import java.awt.event.*;

public class ChatappClient {
    
    private static int port = 1234;
    JFrame window = new JFrame("Chat");
    JButton sendBox = new JButton("Send");
    JTextField inputMsg = new JTextField(35);
    JTextArea outputMsg = new JTextArea(10, 35);
    private static BufferedReader streamIn;
    private static PrintStream streamOut;
    
    public static void main(String[] args) throws Exception{
        ChatappClient client = new ChatappClient();
        client.window.setVisible(true);
        client.window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        client.run();        
    }
    
    public ChatappClient(){
        
        inputMsg.setSize(40, 20);
        sendBox.setSize(5, 10);
        outputMsg.setSize(35, 50);
        inputMsg.setEditable(false);
        outputMsg.setEditable(false);
        window.getContentPane().add(inputMsg, "South");
        window.getContentPane().add(outputMsg, "East");
        window.getContentPane().add(sendBox, "West");
        window.pack();
        sendBox.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                streamOut.println(inputMsg.getText());
                inputMsg.setText("");
            }
        });
        inputMsg.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                streamOut.println(inputMsg.getText());
                inputMsg.setText("");
            }
        });           
    }
    
    private String getUsername(){
        return JOptionPane.showInternalInputDialog(window, "Server IP Address:", "Welcome to Chat", JOptionPane.QUESTION_MESSAGE);
    }
    
    private void run() throws IOException{
        Socket clientSocket = new Socket("localhost", port);
        streamIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        streamOut = new PrintStream(clientSocket.getOutputStream(), true);
    
        while(true){
            String line = streamIn.readLine();
            if(line.startsWith("Username")){
                streamOut.println(getUsername());
            }else if(line.startsWith("Welcome")){
                inputMsg.setEditable(true);
            }else if(line.startsWith("From")){
                outputMsg.append(line.substring(10)+ "\n");
            }
        }   
    }
}




Is This A Good Question/Topic? 0
  • +

Replies To: Chat using sockets(Single server with multiple clients)

#2 giggly kisses  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 80
  • View blog
  • Posts: 391
  • Joined: 29-March 09

Re: Chat using sockets(Single server with multiple clients)

Posted 30 April 2012 - 03:49 PM

I'm sorry but what do you mean by "it doesn't work", what isn't working? You said something about JOptionPane not working, do you mean it's not showing up? Are you having trouble getting the users input from JOptionPane? Are you getting any error messages when the program runs and you perform a specific task? We need more detail to help you.
Was This Post Helpful? 0
  • +
  • -

#3 Saya_26  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 40
  • Joined: 07-November 11

Re: Chat using sockets(Single server with multiple clients)

Posted 30 April 2012 - 03:57 PM

Oh, sorry.. Even though the Chat interface appears.. The JOptionPane dialog box doesn't appear. The error I get is, "JOptionPane: parentComponent does not have a valid parent".
Was This Post Helpful? 0
  • +
  • -

#4 IamTw_  Icon User is offline

  • D.I.C Head

Reputation: 32
  • View blog
  • Posts: 238
  • Joined: 25-February 11

Re: Chat using sockets(Single server with multiple clients)

Posted 30 April 2012 - 04:41 PM

Hi

Talking about chat app, take a look at this for you reference.
It is one of the best tutorials you will find as a beginner, it explains pretty good what's going on.

http://www.dreaminco...r-gui-optional/
Was This Post Helpful? 1
  • +
  • -

#5 Saya_26  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 40
  • Joined: 07-November 11

Re: Chat using sockets(Single server with multiple clients)

Posted 30 April 2012 - 05:17 PM

Thanks.. I've seen the post before, and I admit it has helped me quite a bit, but I was hoping if anyone could help me with this particular doubt.
Was This Post Helpful? 0
  • +
  • -

#6 Saya_26  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 40
  • Joined: 07-November 11

Re: Chat using sockets(Single server with multiple clients)

Posted 30 April 2012 - 05:37 PM

Ok, I now know what I did wrong.. I accidentally wrote "JOptionPane.showInternalInputDialog", instead of "showInputDialog".. Anyway, thanks guys..

This post has been edited by Saya_26: 30 April 2012 - 05:38 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1