简体   繁体   English

使用套接字编程的Java中的聊天程序

[英]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. 当连接另一个客户端时,isConnected方法返回true,但是服务器未从服务器获取消息。 please help me as this is my first java program in netbeans, i have just finished studying core java. 请帮助我,因为这是我在netbeans中的第一个Java程序,我刚刚完成了核心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. 在分配ss之后移动while逻辑。

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. 您已经创建了一个位于端口3000ServerSocket ,因此当您尝试创建另一个时,它将尝试将自身绑定到该套接字,但由于您的第一个ss仍坐在那里而无法成功。 You should only create one ServerSocket and grab socket connections off of that one ServerSocket as threads connect to it. 您应该只创建一个ServerSocket并在线程连接到该ServerSocket时从该ServerSocket获取套接字连接。

Does this answer your questions? 这能回答您的问题吗?

ss.accept() will block until it receives a connection. ss.accept()将阻塞,直到接收到连接为止。 How are you connecting to it? 您如何连接到它?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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