简体   繁体   English

无法使用JAVA套接字通过服务器通过双向客户端聊天接收消息…(多线程)

[英]Unable to receive messages in 2 way client chat via Server using JAVA Sockets…(MultiThreaded)

i am having 2 client sockets..each of them having its own AWT.Frame as GUI for chatting.. On the server side i have a ServerSocket with 2 threads created for handling each of the clients.. 我有2个客户端套接字..每个都有自己的AWT.Frame作为聊天的GUI。在服务器端,我有一个ServerSocket,其中创建了2个用于处理每个客户端的线程。

The writing of the msg to the stream is done properly but im unable to read it..and both the threads also terminate(i think because of some Exception mostly..NullPointer but isnt shown on the console) after i click "send" button on both the client windows.. 将msg写入流已正确完成,但我无法读取它。.而且两个线程也终止(我认为主要是因为某些异常。.NullPointer但未在控制台上显示),在我单击“发送”按钮后在两个客户端窗口上..

Code of ChatServer.main() ChatServer.main()的代码

public static void main(String args[])throws IOException
{
    boolean listening=true;
    try
    {
        try
        {
            server=new ServerSocket(12591);
        }catch(IOException e)
        {
            System.out.println("Couldn't listen to specified port as it might be already used by some other service");
            System.exit(1);
        }

        System.out.println("Waiting for some client to initiate connection...");
        //while (listening)
        //{
            new ChatServerThread(server.accept()).start();
            System.out.println("Connected to User1!");

            new ChatServerThread(server.accept()).start();
            System.out.println("Connected to User2!");
        //}

    }catch(SocketException e)
    {
        System.out.println(e.getMessage());
    }
    server.close();
}

Code of ChatServerThread.constructor() and the run() method(ChatServerThread extends Thread) ChatServerThread.constructor()和run()方法的代码(ChatServerThread扩展了Thread)

public ChatServerThread(Socket s)
{
    super("ChatServerThread"+(++count));
    socket = s;

    try
    {
        in=new DataInputStream(socket.getInputStream());
        out=new DataOutputStream(socket.getOutputStream());
    }catch(IOException e)
    {
        System.out.println("Problem getting I/O connection");
        System.exit(1);
    }
}
public void run()
{
    while(true)
    {
        try
        {
            String s = in.readUTF();
            if(s.equals("DISCONNECT~!@#"))
            {
                break;
            }else
            {
                ChatServer.chatMsgs.add(s);
                System.out.println(s);
                //makeClients.c1.display.append(s);
                //makeClients.c2.display.append(s);
                ChatClient.addMsg2Disp(s);
            }
        }catch(IOException e)
        {
            System.out.println("IOException occured");
        }
    }
}

Methods of ChatClient(has GUI): Its constructor, implemented Listener method: ChatClient(具有GUI)的方法:其构造函数,实现了Listener方法:

public ChatClient()
{
    setLayout(new BorderLayout());

    bottomPanel=new Panel(new FlowLayout());
    bottomPanel.add(txtEntry=new TextArea(4,80));
    bottomPanel.add(send=new Button("Send"));
    bottomPanel.add(disconnect=new Button("Disconnect"));

    add(bottomPanel, BorderLayout.SOUTH);

    display=new TextArea();
    //display.setEditable(false);
    add(display, BorderLayout.CENTER);

    try
    {
        client=new Socket(InetAddress.getLocalHost(), 12591);
        in = new DataInputStream(client.getInputStream());
        out = new DataOutputStream(client.getOutputStream());
    }catch(UnknownHostException e)
    {
        System.out.println("Local Host cannot be resolved on which the server is runnig");
        System.exit(1);
    }catch(IOException e)
    {
        System.out.println("Problem acquiring I/O Connection.");
        System.exit(1);
    }

    send.addActionListener(this);
    disconnect.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
    if(ae.getSource().equals(send))
    {
        try
        {
            if(!(txtEntry.getText().trim().equals("")))
            {
                out.writeUTF(txtEntry.getText());
                out.flush();
            }
        }catch(IOException e)
        {
            System.out.println("IOException occured");
        }
    }
    else if(ae.getSource().equals(disconnect))
    {

    }
}
static void addMsg2Disp(String msg)
{
    display.append(msg);
}

and finally there is 1 more class called makeClients which instantiates 2 objs of ChatClient class and sets size, visibility etc of the frame.... 最后还有1个名为makeClients的类,该类实例化ChatClient类的2个objs并设置框架的大小,可见性等。

i think its a big question but unable to figure out why isnt able to receive.. anyone who could help me out..thanks in advance! 我认为这是一个大问题,但无法弄清楚为什么无法接收..任何可以帮助我的人..提前谢谢! :) :)

PS: and it isnt a real app..i am learning JAVA sockets..so just trying to code something like this.. PS:它不是一个真正的应用程序..我正在学习JAVA套接字..所以只是尝试编写类似这样的代码..

It looks like you're problem coule be in your ChatServerThread on this line: 看起来您很麻烦,这是您在ChatServerThread中的这一行:

if (s.equals("DISCONNECT~!@#") || s != null)

The else block will never be executed as s can not be null (if it is a NullPointerException will be thrown when calling the equals method on it. I'm guessing you meant it to be a reference equality check for null : else块将永远不会执行,因为s不能为null (如果它是NullPointerException则在其上调用equals方法时将抛出该异常。我猜您是说它是对null的引用相等检查:

if (s.equals("DISCONNECT~!@#") || s == null)

just a quick fix try 只是一个快速修复尝试

if(s != null ? (s.equals("DISCONNECT~!@#")) :false)

should solve the NullPointerException problem of yours 应该解决您的NullPointerException问题

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

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