简体   繁体   中英

chat program in java using socket programming

here is the server side code of my program, the problem is, its accepting one client. when another client is connected, the isConnected method returns true, but the server does not gets the messages from the server. please help me as this is my first java program in netbeans, i have just finished studying core java.

class Conn extends Thread{
        ServerSocket ss;
        Socket s;
        public void run()
        {
            status.setText(status.getText()+"connecting");
            try{
            while(true)
            {
            s=new Socket();
            ss=new ServerSocket(3000);
            s=ss.accept();
            Read r=new Read(s);
            r.start();
            }
            }catch(Exception e){}
        }

    }
    class Read extends Thread{
        DataInputStream inp;
        PrintStream outp;
        String str;
        Read(Socket s)
        {
            try{
            inp=new DataInputStream(s.getInputStream());
            outp=new PrintStream(s.getOutputStream());
            }catch(Exception sd){}
        }
        public void run()
        {
                status.setText(status.getText()+"\nreading");
            try{
            while(true)
            {
                str=inp.readLine();
                chatwin.append(str);
                outp.println(str);
            }
            }catch(Exception er){}
        }

    }

Move the while logic after the assignment of ss.

try 
{
    ss = new ServerSocket(3000);
    while (ss.isBound())
    {
        s=ss.accept();
        Read r = new Read(s);
        r.start();
    }
}

Your problem is that you can't do this multiple times:

ss = new ServerSocket(3000);

You've already created a ServerSocket that sits at port 3000 , so when you try to make another one, it'll try to bind itself to that socket, and not succeed because your first ss is still sitting there. You should only create one ServerSocket and grab socket connections off of that one ServerSocket as threads connect to it.

Does this answer your questions?

ss.accept() will block until it receives a connection. How are you connecting to it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM