简体   繁体   中英

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..

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..

Code of 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)

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:

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....

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..

It looks like you're problem coule be in your ChatServerThread on this line:

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 :

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

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