I have created a simple client server chat program using socket. I used to run Client program and Server program separately in two eclipse and chat is done through console only. The logic is as below:

                    System1Class (Server)                 |         System2Class (Client)
                 1) SendThreadSys1  Class                 |       1) SendThreadSys2 Class
                 2) ReceivedThreadSys1 Class              |       2) ReceivedThreadSys2 Class  

Here I used 2 threads for each client and server classes. One thread is for sending and one thread is for receiving.
For sending I used Scanner.nextLine() to get the input from console. The program is working properly i.e. the 2 eclipses can communicate with each other through their console, but the problem comes while closing the socket.
I want to closed the socket by sending the string as "999" from SendThreadSys2 class. I tried to put Socket.closed()
in SendThreadSys2 class just after sending "999" but it gave

java.net.SocketException: Socket closed

Same problem occurs if I send "999" from SendThreadSys1 class. I think it is because all the four threads are connecting through a single socket. So how can I put Socket.closed() so as to make the socket closed successfully?

Thanks in advance.

Recommended Answers

All 4 Replies

You have 4 connections throiugh one ServerSocket, but only one per Socket - the difference is important.
It's always a bit messy clsing a Socket connection when you have input/output streams going in both directions. Whichever end closes first will trigger a SocketException at the other end. ALl you can do AFAIK is to send 999 and close the socket. At the other end set a flag when you get the 999, then catch the exception and then ignore it if the flag is set.

Thanks James, I will try to handle the exception. But before doing that I want to know whether there is any way that I can assign value to standard inputstream.
e.g. somthing like

System.in = "999";

I don't know any way to do that, someone else may know?

We can assign value to Standard Inputstream using System.setIn(). But again a new problem comes up when I used this. Anyway for this thread I use exception handling, and for now chatting program is working fine. But I still want to find a solution whithout handling the exception i.e. closing the socket smoothly. So I will create a new Thread explaining my problem

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.