Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: chat application login error

  1. #1
    Junior Member
    Join Date
    Mar 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default chat application login error

    I want to make a chat application in java but when I'm trying to log in to the server it gives me an error or it has unending loop. I cant find the error.

    when I try to log in to the server using the client. the while loop in checkClientMessage() method doesnt stop
    it gives me unending loop like "User "+loginUser[0] +" has logged in" as a message.
    also, it should print "200" when the user can log in, but in the client side, it cannot read "200" and it doesnt read anything. it prints out null string.
    please help me. here are my codes.

    //This is the chat server application
    [CODE]
    package chatfiles;

    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;

    public class ChatServer {
    private JFrame jframe;
    private Container container;
    private JButton jb1;
    private JTextField jtf1;
    private JTextField jtf2;
    private JLabel jl1;

    private ServerSocket serverSocket = null;
    private static Socket socket = null;
    public static void main(String[] args){
    /*try{
    ServerSocket ss = new ServerSocket(1234);
    System.out.println("Server is running on port: "+ss.getLocalPort());
    while(true){
    new serverOn(ss.accept()).start();
    }

    }catch(Exception e){
    System.out.println("error here serverSocket)");
    }*/

    new ChatServer();
    }

    public void stopServer(){
    try{
    serverSocket.close();
    socket.close();
    jb1.setText("Start Server");
    jtf1.setEnabled(true);
    jtf1.setText("");
    jl1.setText("");

    }catch(Exception e){
    System.err.println("error on closing sockets: "+e);
    JOptionPane.showMessageDialog(jframe,"cannot close ServerSocket");
    }
    }

    public void startServer(int port){
    try{
    serverSocket = new ServerSocket(port);
    jl1.setText("server is running on port: "+String.valueOf(port));
    jb1.setText("Stop Server");
    jtf1.setEnabled(false);
    try{
    while(true){
    try{
    socket = serverSocket.accept();
    new serverOn(socket).start();
    jtf2.setText(jtf2.getText().toString() + "a client has connected: \n");
    }catch(Exception b){
    System.err.println("error when client is connecting INSIDE while(true): "+b);
    JOptionPane.showMessageDialog(jframe,"error when client is connecting INSIDE while(true) on port: "+port);
    }
    }
    }catch(Exception a){
    System.err.println("error when client is connecting OUTSIDE while(true): "+a);
    JOptionPane.showMessageDialog(jframe,"error when client is connecting OUTSIDE while(true) on port: "+port);
    }
    }catch(Exception e){
    System.err.println("error on starting server: "+e);
    JOptionPane.showMessageDialog(jframe,"cannot start ServerSocket on port: "+port);
    }
    }

    public ChatServer(){
    jframe = new JFrame("Chat Server Frame");
    jframe.setSize(500,300);
    jframe.setDefaultCloseOperation(jframe.EXIT_ON_CLO SE);

    container = jframe.getContentPane();
    container.setLayout(new GridLayout(2,2));

    jb1 = new JButton("Start Server");

    jtf1 = new JTextField();
    jtf2 = new JTextField();

    jl1 = new JLabel();

    container.add(jb1);
    container.add(jtf1);
    container.add(jl1);
    container.add(jtf2);

    jb1.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    try{
    if(jtf1.getText().toString()!=null){
    try{
    Thread t = new Thread(){
    public void run(){
    try{
    if(jb1.getText().toString().equals("Start Server")){
    if(jtf1.getText().toString().length() > 3 && jtf1.getText().toString().length() < 6){
    startServer(Integer.parseInt(jtf1.getText().toStri ng()));
    }else{
    JOptionPane.showMessageDialog(jframe,"input port > 1024 && port < 60000");
    }

    }else{
    stopServer();
    }
    }catch(Exception aea){
    }
    }
    };
    t.start();
    }catch(Exception ea){
    JOptionPane.showMessageDialog(jframe,"Inside Thread Error()");
    }
    }else{
    JOptionPane.showMessageDialog(jframe,"Input a port number");
    }
    }catch(Exception a){
    JOptionPane.showMessageDialog(jframe,"Input a valid number");
    }
    }
    });


    jframe.setVisible(true);
    }
    }

    class serverOn extends Thread{
    private Socket socket = null;

    private boolean checker = false;
    private static Hashtable<String, serverOn> hashtable = new Hashtable<String, serverOn>();
    private JFrame jframe = new JFrame();

    private BufferedReader br;
    private PrintWriter pw;

    public serverOn(Socket s){
    socket = s;
    try{
    br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    pw = new PrintWriter(socket.getOutputStream(),true);

    }catch(Exception e){
    System.out.println("error here serverOn()");
    }

    }
    public void run(){
    try{
    String line;
    while((line = br.readLine())!=null){
    System.out.println("message: "+line);
    checkClientMessage(line);
    }
    }catch(Exception e){
    System.err.println("error run()"+e);
    }
    }

    public void checkClientMessage(String line){
    try{
    String name = "";
    while(!line.equals("exit")){
    try{
    String lineTemp[] = line.split(" ");
    if(lineTemp[0].equals("login")){
    String temp[] = line.split(" ");
    String loginUser[] = temp[1].split(",");
    checkUser(loginUser[0],loginUser[1]);
    if(checker){
    hashtable.put(loginUser[0],this);
    pw.println("200");
    System.out.println("User "+loginUser[0] +" has logged in.\n");
    checker = false;
    }else{
    pw.println("400");
    }
    }
    if(lineTemp[0].equals("reg")){
    String temp[] = line.split(" ");
    String registerUser[] = temp[1].split(",");
    regUser(registerUser[0],registerUser[1]);
    if(checker){
    hashtable.put(registerUser[0],this);
    System.out.println("User "+registerUser[0] +" registered.\n");
    checker = false;
    }
    }
    if(lineTemp[0].equals("/pm")){
    String PMline[] = line.split(" ");
    String PMmsg ="";
    for(int i = 2; i<PMline.length; i++){
    PMmsg += PMline[i] +" ";
    }
    hashtable.get(PMline[1]).privateMessage(name, PMmsg.trim());
    System.out.println(name + " pm'ed " + PMline[1] + "message: "+PMmsg.trim());

    }else if(lineTemp[0].equals("/bmsg")){
    String BMline[] = line.split(" ");
    String BMmsg = "";
    for(int i = 2; i<BMline.length; i++){
    BMmsg += BMline[i] + " ";
    }
    for(serverOn so : hashtable.values()){
    so.broadcastMessage(name,BMmsg.trim());
    System.out.println(name + " broadcast message: "+BMmsg.trim());
    }
    }
    }catch(Exception e){
    if(!line.equals("exit")){
    System.out.println("error here RUN()");
    JOptionPane.showMessageDialog(jframe,"Error here RUN()");
    }
    }
    }
    }catch(Exception ee){
    }
    }

    public void checkUser(String user, String pass) throws Exception{
    BufferedReader br = new BufferedReader(new FileReader("users.txt"));
    String line = "";
    while((line = br.readLine())!=null){
    String temp[] = line.split(",");
    if(temp[0].equals(user)){
    if(temp[1].equals(pass)){
    pw.println("200");
    checker = true;
    br.close();
    break;
    }else{
    pw.write("400");
    }
    }
    }
    }

    public void privateMessage(String name, String message){
    try{
    pw.println("[PrivateMessage]"+name+":"+message+"\n");
    }catch(Exception e){
    System.out.println("pm message error: "+e);
    }
    }

    public void broadcastMessage(String name, String message){
    try{
    pw.println(name + ":" + message + "\n");
    }catch(Exception e){
    System.out.println("broadcast message error: "+e);
    }
    }

    public void regUser(String user, String pass) throws Exception{
    BufferedWriter bw = new BufferedWriter(new FileWriter("users.txt"));
    bw.write(user+","+pass);
    checker = true;
    pw.write("200");
    bw.flush();
    bw.close();
    }
    }[code]



    //this is the chat client application
    package chatfiles;
     
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
     
    public class ChatClient extends Thread{
    	private JFrame jframe;
    	private Container container;
    	private JButton jb1,jb2,jb3,jb4;
    	private JTextField jtf1,jtf2,jtf3;
    	private JLabel jl1,jl2,jl3;
     
    	private static Socket socket;
     
    	private BufferedReader br;
    	private PrintWriter pw;
     
    	private String messageFromServer = "";
    	private String msgTemp = "";
     
    	private boolean connectorChecker = false;
    	private boolean responseChecker = false;
     
        public static void main(String[] args) {
     
        	new ChatClient(socket).start();
        } 
     
        public void run(){
        	try{
        		while(msgTemp != null){
        			msgTemp = br.readLine();
        			messageFromServer = msgTemp;
        			System.out.println(msgTemp);
        			JOptionPane.showMessageDialog(jframe,"MESSAGE FROM SERVER: "+msgTemp);
        			}
        	}catch(Exception e){
        		JOptionPane.showMessageDialog(jframe,"error run CHATCLIENT()");
        	}
        }	
     
        public ChatClient(Socket sock){
        	jframe = new JFrame("Welcome Frame");
        	jframe.setSize(300,400);
        	jframe.setDefaultCloseOperation(jframe.EXIT_ON_CLOSE);
     
        	container = jframe.getContentPane();
        	container.setLayout(new GridLayout(5,2));
     
        	jb1 = new JButton("Login");
        	jb2 = new JButton("Register");
        	jb3 = new JButton("Connect to server");
        	jb4 = new JButton("Exit");
     
        	jtf1 = new JTextField("");
        	jtf1.setText("");
        	jtf2 = new JTextField("");
        	jtf2.setText("");
        	jtf3 = new JTextField("");
        	jtf3.setText("");
     
        	jl1 = new JLabel("username:");
        	jl2 = new JLabel("password:");
     
        	container.add(jl1);
        	container.add(jtf1);
        	container.add(jl2);
        	container.add(jtf2);
        	container.add(jb1);
        	container.add(jb2);
        	container.add(jtf3);
        	container.add(jb3);
        	container.add(jb4);
     
        	jb3.addActionListener(new ActionListener(){
        		public void actionPerformed(ActionEvent e){
        			try{
        				connectToServer(jtf3.getText().toString());
        				if(connectorChecker){
        					jb3.setEnabled(false);
        					jtf3.setEnabled(false);
        					jb3.setText("connected");
        				}
        			}catch(Exception a){
        				System.err.println("JBUTTON 3 ERROR: "+a);
        			}
        		}
        	});
     
        	jb1.addActionListener(new ActionListener(){
    				public void actionPerformed(ActionEvent e){
    					Thread t = new Thread(){
    						public void run(){
    							try{
    		    				pw.println("login "+jtf1.getText().toString()+","+jtf2.getText().toString());
     
    		    				checkResponse(messageFromServer);
     
    			    			}catch(Exception a){
    			    				System.err.println("JButton 2 login error: "+a);
    			    			}
    						}
    					};
    					t.start();
        			}
        		});
     
        	jb2.addActionListener(new ActionListener(){
        		public void actionPerformed(ActionEvent e){
        			try{
        				jframe.setVisible(false);
        				new ChatRegister(socket);
        			}catch(Exception a){
        				System.err.println("error in register: "+e);
        			}
        		}
        	});
     
        	jb4.addActionListener(new ActionListener(){
        		public void actionPerformed(ActionEvent e){
        			try{
        				pw.close();
        				br.close();
        				socket.close();
        				System.exit(0);
        			}catch(Exception a){
        				JOptionPane.showMessageDialog(jframe,"error sa exit");
        			}
        		}
        	});
        	jframe.setVisible(true);
     
        }
     
        public void checkResponse(String line){
        	try{
        		if(line.equals("200")){
        			JOptionPane.showMessageDialog(jframe,"sucessfully logged in");
        			connectorChecker = true;
        		}else if(line.equals("400")){
        			JOptionPane.showMessageDialog(jframe,"wrong username / password");
        			connectorChecker = false;
        		}else{
        			JOptionPane.showMessageDialog(jframe,"wrong output from server");
        			JOptionPane.showMessageDialog(jframe,line);
        			connectorChecker = false;
        		}
        	}catch(Exception e){
        		JOptionPane.showMessageDialog(jframe,"checkResponse() error");
        	}
        }
     
        public void connectToServer(String port){
        	try{
        		int a = Integer.parseInt(port);
        		socket = new Socket("localhost",a);
     
        		br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    			pw = new PrintWriter(socket.getOutputStream(),true);
     
        		connectorChecker = true;
        	}catch(Exception e){
        		System.err.println("connect to server error: "+e);
        	}
        }
     
        public void closeConnection(){
        	try{
        		socket.close();
        		br.close();
        		pw.close();
        	}catch(Exception e){
        		System.err.println("error in closing connection."+e);
        	}
        }
     
    }
     
    class ChatRegister{
    	private JFrame jframe;
    	private Container container;
    	private JLabel jl1,jl2,jl3;
    	private JButton jb1,jb2;
    	private JTextField jtf1,jtf2,jtf3;
    	public ChatRegister(final Socket socket){
    		jframe = new JFrame("Chat Register Frame");
    		jframe.setSize(300,400);
    		jframe.setDefaultCloseOperation(jframe.EXIT_ON_CLOSE);
     
    		container = jframe.getContentPane();
    		container.setLayout(new GridLayout(4,2));
     
    		jl1 = new JLabel("username:");
    		jl2 = new JLabel("password:");
    		jl3 = new JLabel("re-type password:");
     
    		jb1 = new JButton("Register");
    		jb2 = new JButton("Clear");
     
    		jtf1 = new JTextField("");
    		jtf2 = new JTextField("");
    		jtf3 = new JTextField("");
     
    		container.add(jl1);
    		container.add(jtf1);
    		container.add(jl2);
    		container.add(jtf2);
    		container.add(jl3);
    		container.add(jtf3);
    		container.add(jb1);
    		container.add(jb2);
     
    		jb1.addActionListener(new ActionListener(){
    			public void actionPerformed(ActionEvent e){
    				try{
    					if(jtf2.getText().toString().equals(jtf3.getText().toString())){
    						if(jtf2.getText().toString().length() > 5 && jtf2.getText().toString().length() < 15){
    							//dos.writeChars("reg "+jtf1.getText().toString()+","+jtf2.getText().toString());
    							JOptionPane.showConfirmDialog(jframe,"Successfuly registered! Select OK to procceed");
    							jframe.setVisible(false);
    							new ChatClient(socket);
    						}else{
    							JOptionPane.showMessageDialog(jframe,"passwords should be greater than 5 and less than 15 characters.");
    						}
    					}else{
    						JOptionPane.showMessageDialog(jframe,"passwords are not equal.");
    					}
    				}catch(Exception a){
    					System.err.println("error on register button"+a);
    				}
    			}
    		});
     
    		jb2.addActionListener(new ActionListener(){
    			public void actionPerformed(ActionEvent e){
    				try{
    					jtf1.setText("");
    					jtf2.setText("");
    					jtf3.setText("");
    				}catch(Exception a){
    					System.err.println("error in clear text register: "+a);
    				}
    			}
    		});
    		jframe.setVisible(true);
    	}
    }
     
    class ClientFrame{
     
    }
     
    please help me. thank you for your help :)


  2. #2
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: chat application login error

    If you state: while(!line.equals("exit")), then obviously it's going to infinitely loop until your string equals "exit".
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: chat application login error

    Can you fix the ending code tag on the server code? Its missing the /

  4. #4
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: chat application login error

    Please don't multi-post within the forum itself.
    If you read the forum rules, you would have noticed that it is not allowed here.
    From here on in, please stick to this thread.

    Multiposted here:
    http://www.javaprogrammingforums.com...gin-error.html
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: chat application login error

    First and VERY IMPORTANT you MUST add calls to printStaceTrace() to EVERY catch block so that you see what and where the problems with your code are.

Similar Threads

  1. mobile chat application
    By teemone2001 in forum Java Theory & Questions
    Replies: 1
    Last Post: July 21st, 2011, 03:33 AM
  2. Server-Client Chat application using UDP
    By weakprogrammer in forum Java Networking
    Replies: 3
    Last Post: July 1st, 2011, 02:35 PM
  3. Chat application Sign in Problem (maybe : Exception)
    By aymane-tech in forum Java Networking
    Replies: 1
    Last Post: March 23rd, 2011, 11:01 AM
  4. Chat application problem
    By fembiz in forum Java Networking
    Replies: 1
    Last Post: December 11th, 2009, 05:21 AM
  5. Replies: 1
    Last Post: October 20th, 2009, 06:31 AM