5 Replies - 2122 Views - Last Post: 02 August 2012 - 10:00 AM Rate Topic: -----

#1 Randor  Icon User is offline

  • D.I.C Head

Reputation: 10
  • View blog
  • Posts: 106
  • Joined: 12-October 10

problem with Chat program

Posted 30 July 2012 - 12:35 PM

I found a tutorial on youtube on how to do a chatroom, in my attempts to learn Java I took this on. I followed along and it does work, however, I am finding an issue, I am trying to solve it but I cannot seem to figure out why it is happening, let alone fix it.

The code is such:

Chat_Server
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;



/**
 *
 * @author Bob
 */
public class Chat_Server {
    
    public static ArrayList<Socket> ConnectionArray = new ArrayList<>();
    public static ArrayList<String> CurrentUsers = new ArrayList<>();
    
    
    public static void main(String[] args) throws IOException {
        
        try {
            
            final int PORT = 444;
            ServerSocket SERVER = new ServerSocket(PORT);
            System.out.println("Waiting For Chatters");
            
            while (true) {
                
                Socket SOCK = SERVER.accept();
                ConnectionArray.add(SOCK);
                
                System.out.println("Client Connected from: " + SOCK.getLocalAddress().getHostName());
                
                AddUserName(SOCK);
                
                Chat_Server_Return CHAT = new Chat_Server_Return(SOCK);
                
                Thread X = new Thread(CHAT);
                X.start();             
                
            }
     
            
        } catch(Exception X) { System.out.println("here" + X); }
            
    }

    public static void AddUserName(Socket X) throws IOException {

        Scanner INPUT = new Scanner(X.getInputStream());
        String UserName = INPUT.nextLine();
        CurrentUsers.add(UserName);
        
        for(int i = 1; i <= Chat_Server.ConnectionArray.size(); i++) {
            
            Socket TEMP_SOCK = (Socket) Chat_Server.ConnectionArray.get(i-1);
            PrintWriter OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
            OUT.println("#?!"+CurrentUsers);
            OUT.flush();
            
        }
        
        
    }
    
    
 }



Chat_Server_Return
import java.io.*;
import java.net.*;
import java.util.Scanner;




/**
 *
 * @author Bob
 */
public class Chat_Server_Return implements Runnable {

    Socket SOCK;
    private Scanner INPUT;
    private PrintWriter OUT;
    String MESSAGE = "";
    
    public Chat_Server_Return(Socket X) {
        
        this.SOCK = X;
    }
    
    public void CheckConnection() throws IOException {
        
        if(!SOCK.isConnected()) {
            
            for(int i = 1; i <= Chat_Server.ConnectionArray.size(); i++) {
                
                if (Chat_Server.ConnectionArray.get(i) == SOCK) {
                    
                    Chat_Server.ConnectionArray.remove(i);
                    
                }
            }
            
             for(int i = 1; i <= Chat_Server.ConnectionArray.size(); i++) {
                 
                 Socket TEMP_SOCK  =(Socket) Chat_Server.ConnectionArray.get(i-1);
                 PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
                 TEMP_OUT.println(TEMP_SOCK.getLocalAddress().getHostName() + "Disconnected!");
                 TEMP_OUT.flush();
                 //show disconnect at server
                 System.out.println(TEMP_SOCK.getLocalAddress().getHostName() + "Disconnected!");
                 
             }
            
            
        }
        
    }
    
    @Override
    public void run() {
        
        try {
            try {
                
                INPUT = new Scanner(SOCK.getInputStream());
                OUT=  new PrintWriter(SOCK.getOutputStream());
                
                while(true) {
                    
                    CheckConnection();
                    
                    if(!INPUT.hasNext()) { return; }
                    
                    MESSAGE = INPUT.nextLine();
                    
                    System.out.println("Client Said: "+MESSAGE);
                    
                    for(int i = 1; i <= Chat_Server.ConnectionArray.size(); i++) {

                        Socket TEMP_SOCK  =(Socket) Chat_Server.ConnectionArray.get(i-1);
                        PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
                        System.out.println("Sent To: " + TEMP_SOCK.getLocalAddress().getHostName());
                        TEMP_OUT.println(MESSAGE);
                        TEMP_OUT.flush();
                        //show disconnect at server
                        


                    }                    
                    
                }
            } finally { SOCK.close(); }
        } catch(Exception X) { System.out.print(X); } 
        
    }
    
   
}



Chat_Client
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.util.*;

/**
 *
 * @author Bob
 */
public class Chat_Client implements Runnable {
    
    Socket SOCK;
    Scanner INPUT;
    Scanner SEND = new Scanner(System.in);
    PrintWriter OUT;

    Chat_Client(Socket X) {
        this.SOCK = X;
    }

    @Override
    public void run() {
        
        try {
            
            try {
                
                INPUT = new Scanner(SOCK.getInputStream());
                OUT = new PrintWriter(SOCK.getOutputStream());
                OUT.flush();
                CheckStream();
                
            }
            finally
            {
                SOCK.close();
            }
        }
        catch(Exception X) { System.out.print(X); }
       
    }
    
    public void DISCONNECT() throws IOException {
        
        OUT.println(Chat_GUI.UserName + " has disconnected!");
        OUT.flush();
        SOCK.close();
        JOptionPane.showMessageDialog(null,"You have Disconnected!");
        System.exit(0);       
        
    }
    
    public void CheckStream() {
        
        while(true) { RECEIVE(); }
        
    }
    
    public void RECEIVE() {
        
        if(INPUT.hasNext()) {
            
            String MESSAGE = INPUT.nextLine();
            
            if(MESSAGE.contains("#?!")) {
                
                String TEMP1 = MESSAGE.substring(3);
                TEMP1 = TEMP1.replace("[","");
                TEMP1 = TEMP1.replace("]","");
                
                String[] CurrentUsers = TEMP1.split(", ");
                
                Chat_GUI.JL_ONLINE.setListData(CurrentUsers);
            }
            else 
            {
                Chat_GUI.TA_CONVERSATION.append(MESSAGE + "\n");
            }
        }
    }
    
    public void SEND(String X) {
        
        OUT.println(Chat_GUI.UserName + ": " + X);
        OUT.flush();
        Chat_GUI.TF_Message.setText("");
        
    }
    
}



Chat_GUI
import javax.swing.*;
import java.io.PrintWriter;
import java.net.*;

/**
 *
 * @author Bob
 */
public class Chat_GUI {
    
    private static Chat_Client ChatClient;
    public static String UserName = "Anonymous";
    
    //GUI Globals
    public static JFrame MainWindow = new JFrame();
    public static JButton B_ABOUT = new JButton();
    public static JButton B_CONNECT = new JButton();
    public static JButton B_DISCONNECT = new JButton();
    public static JButton B_HELP = new JButton();
    public static JButton B_SEND = new JButton();
    public static JLabel L_Message = new JLabel("Message: ");
    public static JTextField TF_Message = new JTextField(20);
    public static JLabel L_Conversation = new JLabel();
    public static JTextArea TA_CONVERSATION  = new JTextArea();
    public static JScrollPane SP_CONVERSATION  = new JScrollPane();
    public static JLabel L_ONLINE = new JLabel();
    public static JList JL_ONLINE = new JList();
    public static JScrollPane SP_ONLINE  = new JScrollPane();
    public static JLabel L_LoggedInAs = new JLabel();
    public static JLabel L_LoggedInAsBox = new JLabel();
    
    
    //GUI Global Login Window
    public static JFrame LogInWindow = new JFrame();
    public static JTextField TF_UserNameBox = new JTextField(20);
    public static JButton B_ENTER = new JButton();
    public static JLabel L_EnterUserName= new JLabel("Enter Username: ");
    public static JPanel P_Login = new JPanel();
    
    
    public static void main(String args[]) {
     
      BuildMainWindow();
      Initialize();
    
    }
    
    public static void BuildMainWindow() {
        
        Mainwindow.setTitle(UserName + "'s Chat Box");
        Mainwindow.setSize(450,500);
        Mainwindow.setResizable(false);
        ConfigureMainWindow();
        MainWindow_Action();
        Mainwindow.setVisible(true);
        
    }
    
    public static void BuildLogInWindow() {
 
        LogInwindow.setTitle("Whats Your Name? ");
        LogInwindow.setSize(400,100);
        LogInwindow.setResizable(false);
        P_Login = new JPanel();
        P_Login.add(L_EnterUserName);
        P_Login.add(TF_UserNameBox);
        P_Login.add(B_ENTER);
        LogInwindow.add(P_Login);
        System.out.println("Got Here");
        Login_Action();
        LogInwindow.setVisible(true);
        
    }
    
    public static void ConfigureMainWindow() {
        
        Mainwindow.setBackground(new java.awt.Color(255,255,255));
        Mainwindow.setSize(500,320);
        Mainwindow.getContentPane().setLayout(null);
        
        B_SEND.setBackground(new java.awt.Color(0,0,255));
        B_SEND.setForeground(new java.awt.Color(255,255,255));
        B_SEND.setText("SEND");
        Mainwindow.getContentPane().add(B_SEND);
        B_SEND.setBounds(250,40,81,25);
        
        B_DISCONNECT.setBackground(new java.awt.Color(0,0,255));
        B_DISCONNECT.setForeground(new java.awt.Color(255,255,255));
        B_DISCONNECT.setText("DISCONNECT");
        Mainwindow.getContentPane().add(B_DISCONNECT);
        B_DISCONNECT.setBounds(10,40,110,25);
        
        B_CONNECT.setBackground(new java.awt.Color(0,0,255));
        B_CONNECT.setForeground(new java.awt.Color(255,255,255));
        B_CONNECT.setText("CONNECT");
        Mainwindow.getContentPane().add(B_CONNECT);
        B_CONNECT.setBounds(130,40,110,25);
        
        B_HELP.setBackground(new java.awt.Color(0,0,255));
        B_HELP.setForeground(new java.awt.Color(255,255,255));
        B_HELP.setText("HELP");
        Mainwindow.getContentPane().add(B_HELP);
        B_HELP.setBounds(420,40,70,25);
        
        B_ABOUT.setBackground(new java.awt.Color(0,0,255));
        B_ABOUT.setForeground(new java.awt.Color(255,255,255));
        B_ABOUT.setText("ABOUT");
        Mainwindow.getContentPane().add(B_ABOUT);
        B_ABOUT.setBounds(340,40,75,25);
        
        L_Message.setText("Message:");
        Mainwindow.getContentPane().add(L_Message);
        L_Message.setBounds(10,10,60,20);
        
        TF_Message.setForeground(new java.awt.Color(0,0,255));
        TF_Message.requestFocus();
        Mainwindow.getContentPane().add(TF_Message);
        TF_Message.setBounds(70,4,260,30);
        
        L_Conversation.setHorizontalAlignment(SwingConstants.CENTER);
        L_Conversation.setText("Conversation");
        Mainwindow.getContentPane().add(L_Conversation);
        L_Conversation.setBounds(100,70,140,16);
        
        TA_CONVERSATION.setColumns(20);
        TA_CONVERSATION.setFont(new java.awt.Font("Tahoma",0,12));
        TA_CONVERSATION.setForeground(new java.awt.Color(0,0,255));
        TA_CONVERSATION.setLineWrap(true);
        TA_CONVERSATION.setRows(5);
        TA_CONVERSATION.setEditable(false);
        
        SP_CONVERSATION.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        SP_CONVERSATION.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        SP_CONVERSATION.setViewportView(TA_CONVERSATION);
        Mainwindow.getContentPane().add(SP_CONVERSATION);
        SP_CONVERSATION.setBounds(10,90,330,180);
        
        L_ONLINE.setHorizontalAlignment(SwingConstants.CENTER);
        L_ONLINE.setText("Currently Online");
        L_ONLINE.setToolTipText("");
        Mainwindow.getContentPane().add(L_ONLINE);
        L_ONLINE.setBounds(350,70,130,16);
        
        JL_ONLINE.setForeground(new java.awt.Color(0,0,255));
        
        SP_ONLINE.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        SP_ONLINE.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        SP_ONLINE.setViewportView(JL_ONLINE);
        Mainwindow.getContentPane().add(SP_ONLINE);
        SP_ONLINE.setBounds(350,90,130,180);
        
        L_LoggedInAs.setFont(new java.awt.Font("Tahoma", 0, 12));
        L_LoggedInAs.setText("Currently Logged In As:");
        Mainwindow.getContentPane().add(L_LoggedInAs);
        L_LoggedInAs.setBounds(348,0,140,15);
        
        L_LoggedInAsBox.setHorizontalAlignment(SwingConstants.CENTER);
        L_LoggedInAsBox.setFont(new java.awt.Font("Tahoma",0,12));
        L_LoggedInAsBox.setForeground(new java.awt.Color(255,0,0));
        L_LoggedInAsBox.setBorder(BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
        Mainwindow.getContentPane().add(L_LoggedInAsBox);
        L_LoggedInAsBox.setBounds(340,17,150,20);
        
    }
    
    public static void Initialize() {
        
        B_SEND.setEnabled(false);
        B_DISCONNECT.setEnabled(false);
        B_CONNECT.setEnabled(true);
        
    }
    
    public static void Login_Action() {
        
        B_ENTER.addActionListener(
                
                new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ACTION_B_ENTER(); } }
                
                );
    }
    
    public static void ACTION_B_ENTER() {
        
        if(!TF_UserNameBox.getText().equals("")) {
            
            UserName = TF_UserNameBox.getText().trim();
            L_LoggedInAsBox.setText(UserName);
            Chat_Server.CurrentUsers.add(UserName);
            Mainwindow.setTitle(UserName +"'s Chat Box");
            LogInwindow.setVisible(false);
            B_SEND.setEnabled(true);
            B_DISCONNECT.setEnabled(true);
            B_CONNECT.setEnabled(false);
            Connect();
            
        } else { JOptionPane.showMessageDialog(null, "You must enter a name!"); }
        
    }
    
    public static void Connect() {
        
        try {
           
            final int PORT = 444;
            final String HOST = "localhost";
            Socket SOCK = new Socket(HOST, PORT);
            System.out.println("Server Connected to: " + HOST);
            
            ChatClient = new Chat_Client(SOCK);
            
            PrintWriter OUT = new PrintWriter(SOCK.getOutputStream());
            OUT.println(UserName);
            OUT.flush();
            
            Thread X = new Thread(ChatClient);
            X.start();
         }
        catch(Exception X)
        {
            System.out.print(X);
            JOptionPane.showMessageDialog(null,"Server Not Responding");
            System.exit(0);
        }
        
        
    }
    
    public static void MainWindow_Action() {
        
                B_SEND.addActionListener(
                
                    new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ACTION_B_SEND(); } }
                
                );
                
                B_DISCONNECT.addActionListener(
                
                    new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ACTION_B_DISCONNECT(); } }
                
                );
                
                B_CONNECT.addActionListener(
                
                    new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BuildLogInWindow(); } }
                
                );
                
                B_HELP.addActionListener(
                
                    new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ACTION_B_HELP(); } }
                
                );
                
                B_ABOUT.addActionListener(
                
                    new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ACTION_B_ABOUT(); } }
                
                );
        
        
    }
    
    public static void ACTION_B_SEND() {
        
        if(!TF_Message.getText().equals("")) {
            ChatClient.SEND(TF_Message.getText());
            TF_Message.requestFocus();
            
        }
    }
    
    public static void ACTION_B_DISCONNECT() {
        
        try
        {
            ChatClient.DISCONNECT();
        }
        catch(Exception Y) { Y.printStackTrace(); }
    }
    
    
    public static void ACTION_B_HELP() {
        
        JOptionPane.showMessageDialog(null,"Multi client chat program");
        
    }
    
        public static void ACTION_B_ABOUT() {
        
        JOptionPane.showMessageDialog(null,"Multi client chat program");
        
    }
    
}


Now, I did my very best to go line for line, then i want to improve on it and try to change things. however, the problem I have is that when you log into the chat, then everyone leaves, if you try to reenter i get the following error:

java.net.SocketException: Socket is closed

it is coming from the main class in Chat_Server(I figured it out with the "here" addition into the exception) but I cannot figure out why it is doing it.

Is the error saying there was an exception so it is closed the socket, or that the socket is closed so THATS the exception? and if so, why?

I am not looking for anyone to write the code for me as that would defeat the purpose of using it to learn, but if anyone can steer me in the right direction I would be much oblidged.

Thank you,

Bob

Is This A Good Question/Topic? 0
  • +

Replies To: problem with Chat program

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: problem with Chat program

Posted 30 July 2012 - 12:59 PM

Not to preach for my parish but I don't really like that code.

Why is everyting static in Chat_GUI ?

     if(INPUT.hasNext()) {  
        String MESSAGE = INPUT.nextLine();  


if INPUT.hasNext() read nextLine()
check for INPUT.hasNextLine() or simply read nextLine() you will wait there

The code does not respect Java naming conventions

 for(int i = 1; i <= Chat_Server.ConnectionArray.size(); i++) {  
     Socket TEMP_SOCK = (Socket) Chat_Server.ConnectionArray.get(i-1);  
     PrintWriter OUT = new PrintWriter(TEMP_SOCK.getOutputStream());  


why not making a for() starting at 0 as verybody does instead of getting(i-1) ?
why re-creating a new OUT every time, why not using the already existing one ? I think this is your problem by the way associating a new channel to the OutputStream that already has one

Find a better example

...
Was This Post Helpful? 2
  • +
  • -

#3 Randor  Icon User is offline

  • D.I.C Head

Reputation: 10
  • View blog
  • Posts: 106
  • Joined: 12-October 10

Re: problem with Chat program

Posted 31 July 2012 - 11:58 AM

pbl,

Thank you for the critiquing, I am moving onto what I hope is a better teaching tool. It is hard to find a solid tutorial on sockets, networking and such. I am also trying to learn about threads and those seem to be the way to go as well.

Have a good day.
Was This Post Helpful? 0
  • +
  • -

#4 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2717
  • View blog
  • Posts: 11,428
  • Joined: 20-September 08

Re: problem with Chat program

Posted 31 July 2012 - 01:09 PM

Have a look at the following. It will give you a solid framework upon which to build client/server apps

http://technojeeves....-david-flanagan
Was This Post Helpful? 1
  • +
  • -

#5 deaththekid111  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 02-August 12

Re: problem with Chat program

Posted 02 August 2012 - 07:00 AM

Here is a easy chat program just edit it to do what you want but it is working
//class for server 
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;



public class Server extends JFrame{
	
	private JTextField userText;
	private JTextArea chatWindow;
	private ObjectOutputStream output;	
	private ObjectInputStream input;
	private ServerSocket server;
	private Socket connection;
	
	
	//constructor 
	public Server() {
		super("Xanders Server");
		userText = new JTextField();
		userText.setEditable(false);
		userText.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent event){
						sendMessage(event.getActionCommand());
						userText.setText("");
					} 
				}
		);
		add(userText, BorderLayout.NORTH);
		chatWindow = new JTextArea();
		add(new JScrollPane(chatWindow));
		setSize(300,150);
		setVisible(true);
	}
	//Set up and run the server 
	public void startRunning(){
		try{
			server = new ServerSocket(6789,100);
			while(true){
				try{
					waitForConnection();
					setupStreams();
					whileChatting();
				}catch(EOFException eofException){
					showMessage("\n Server Ended the Conection");
				}finally{
					closeCon();
				}
			}
		
		}catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	//wait for connection, then display connection information
	private void waitForConnection() throws IOException{
		showMessage("Waiting for someone to connect...");
		connection = server.accept();
		showMessage("\n Now Connected to" +connection.getInetAddress().getHostName());
	} 
	//Get Stream to send and receive Data
	private void setupStreams() throws IOException{
		output = new ObjectOutputStream(connection.getOutputStream());
		output.flush();
		input = new ObjectInputStream(connection.getInputStream());
		showMessage("\n Your streams are now setup! \n");	
		
	}
	//during the chat 
	private void whileChatting() throws IOException{
		String message = "You are now connected like a boss :)/>";
		sendMessage(message);
		ableToType(true);
		do{
			//have a conversation 
			try{
				message = (String) input.readObject();
				showMessage("\n" + message);				
			}catch(ClassNotFoundException classNotFoundException){
				showMessage("\n Cant identify what the User sent :(/>");
			}
		}while(!message.equals("CLIENT - END"));
		
	}
	//closes streams and server after you are done chanting 
	public void closeCon(){
		showMessage("\n Closing connections... \n");
		ableToType(false);
		try{
			output.close();
			input.close();
			connection.close();
		}catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	//Send a message to client
	private void sendMessage(String message){
		try{
			output.writeObject("SERVER -" + message);
			output.flush();
			showMessage("\nSERVER -" + message);
		}catch(IOException ioEception){
			chatwindow.append("\n ERROR Cant send that message");
		}
		
	}
	// Updates chatWindow
	private void showMessage(final String text){
		SwingUtilities.invokeLater(
			new Runnable() {
				public void run() {
					chatwindow.append(text);
				}
			}
		);
	}
	//lets the user type into the box
	public void ableToType(final boolean tof){
		SwingUtilities.invokeLater(
			new Runnable() {
				public void run() {
					userText.setEditable(tof);
				}
			}
		);
	}
}

//main method for server seprate class as server
import javax.swing.JFrame;

public class serverTest {
	public static void main(String[] args){
		Server test = new Server();
		test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		test.startRunning();
	}

}
//client class 
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Client extends JFrame{
	
	private JTextField userText;
	private JTextArea chatWindow;
	private ObjectOutputStream output;
	private ObjectInputStream input;
	private String message = "";
	private String serverIP;
	private Socket connection;
	
	
	//Constructor 
	public Client(String host){
		super("Client");
		serverIP = host;
		userText = new JTextField();
		userText.setEditable(false);
		userText.addActionListener(
				new ActionListener() {
					public void actionPerformed(ActionEvent event){
						sendMessage(event.getActionCommand());
						userText.setText("");
					}
				}
		);
		add(userText, BorderLayout.NORTH);
		chatWindow = new JTextArea();
		add(new JScrollPane(chatWindow), BorderLayout.CENTER);
		setSize(300,150);
		setVisible(true);
	}
	
	//Connect to server
	public void startRunning(){
		try{
			connectTOServer();
			setupStreams();
			whileChatting();
		}catch(EOFException eofException){
			showMessage("\n Client terminated the connection");
		}catch(IOException ioException){
			ioException.printStackTrace();
		}finally{
			closeCon();
		
		}
	}
	//connect to server
	private void connectTOServer() throws IOException{
		showMessage("Attempting Connection... \n");
		connection = new Socket(InetAddress.getByName(serverIP), 6789);
		showMessage("Connected to" + connection.getInetAddress().getHostName());
	}
	//set up streams to send and receive messages
	private void setupStreams() throws IOException{
		output = new ObjectOutputStream(connection.getOutputStream());
		output.flush();
		input = new ObjectInputStream(connection.getInputStream());
		showMessage("\n Your streams are now ready! \n");
		
	}
	//While chatting with server
	private void whileChatting() throws IOException{
		ableToType(true);
		do{
			try{
				message = (String) input.readObject();
				showMessage("\n" + message);
			}catch(ClassNotFoundException classNotFoundException){
				showMessage("\n Object type not Known?");
			}
		}while(!message.equals("SERVER - END"));
	}
	//close the streams and sockets 
	private void closeCon(){
		showMessage("\n Closing Connection...");
		ableToType(false);
		try{
			output.close();
			input.close();
			connection.close();
		}catch(IOException ioException){
			ioException.printStackTrace();
		}
		
	}
	
	//send messages to server
	private void sendMessage(String message){
		try{
			output.writeObject("CLIENT -" + message);
			output.flush();
			showMessage("\n CLIENT - " + message);
		}catch(IOException ioException){
			chatwindow.append("\n ERROR Conection lost");
		}
	}
	
	//change/update ChatWindow
	// Updates chatWindow
	private void showMessage(final String text){
		SwingUtilities.invokeLater(
			new Runnable() {
				public void run() {
					chatwindow.append(text);
				}
			}
		);
	}
	//lets the user type into the box
	public void ableToType(final boolean tof){
		SwingUtilities.invokeLater(
			new Runnable() {
				public void run() {
					userText.setEditable(tof);
				}
			}
		);
	}
}
//client main method seprate class work off this one and add what you want
import javax.swing.JFrame;

public class ClientTest {
	public static void main(String[] args){
		Client ClientTest;
		ClientTest = new Client("127.0.0.1");
		ClientTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		ClientTest.startRunning();		
	}
	
}




Have Fun :)
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: problem with Chat program

Posted 02 August 2012 - 10:00 AM

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

Page 1 of 1