Why does the simple chat Server-Client always give me a BindException? - java

Why does the code below gives the following exception:
java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
at java.net.ServerSocket.bind(ServerSocket.java:376)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at chap15.VerySimpleChatServer.go(VerySimpleChatServer.java:42)
at chap15.VerySimpleChatServer.main(VerySimpleChatServer.java:36)
I tried compiling it with netbeans. I created a project and put both classes inside it.
This is an example of the book "Head First Java", chapter 15
SERVER:
package chap15;
import java.io.*;
import java.net.*;
import java.util.*;
public class VerySimpleChatServer
{
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSOcket) {
try {
sock = clientSOcket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
} catch (Exception ex) { ex.printStackTrace(); }
}
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
tellEveryone(message);
}
} catch (Exception ex) { ex.printStackTrace(); }
}
}
public static void main(String[] args) {
new VerySimpleChatServer().go();
}
public void go() {
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(5000);
while(true) {
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connection");
}
} catch (Exception ex) { ex.printStackTrace(); }
}
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception ex) { ex.printStackTrace(); }
}
}
}

The code "as posted in here" works.
You must have an old thread stuck or a process that is stuck somewhere. This happens if you were debugging it and didn't give it a chance to shut down properly.

Because something else is listening at the port, probably a prior instance of your own program that you haven't terminated yet. Or else you terminated it but there are still ports in TIME_WAIT state, which lasts for two minutes after the last inbound connection is closed.

Related

Java: Socket Closed Error while using thread

I am building a multithread chat server.
The multi-threaded server (Manager Class) could serve many clients. It receives a message from a client, and broadcast to all clients.
The client (Peer Class) have two threads - SendThread for sending a message to the server. ReceiveThread to listen to the server broadcast.
However, while running the client program, it catches the exception and says that socket closed.
My code for the server class is below:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Manager {
public int port;
public ArrayList<Socket> clients;
public Manager(int port) throws IOException {
this.port = port;
this.clients = new ArrayList<>();
try (ServerSocket server = new ServerSocket(port)){
System.out.println("Waiting for client connection-");
while (true){
Socket client = server.accept();
clients.add(client);
System.out.println("Client applies for connection");
Thread t = new Thread(new serverClientThread(client));
t.start();
}
}
}
public class serverClientThread implements Runnable {
private Socket client;
public serverClientThread(Socket client){
this.client = client;
}
#Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
while (true){
// read
String line = reader.readLine();
if (line != null){
System.out.println("I received "+line);
// write
// broadcast
broadcast("I received " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// broadcast the message to all clients
public synchronized void broadcast(String message) throws IOException {
for (Socket client:this.clients){
if (client.isClosed()){
continue;
}
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()))){
writer.write("I received " + message);
writer.newLine();
writer.flush();
}
}
}
}
The code of the client class is below:
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Peer {
public String hostname;
public int port;
public Peer(String hostname, int port){
this.hostname = hostname;
this.port = port;
try (Socket socket = new Socket(hostname, port)){
// create writer
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Thread t1 = new Thread(new SendThread(writer));
Thread t2 = new Thread(new ReceiveThread(reader));
t1.start();
t2.start();
} catch (UnknownHostException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public class SendThread implements Runnable{
private BufferedWriter writer;
public SendThread(BufferedWriter writer){
this.writer = writer;
}
#Override
public void run() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a String: ");
String str = sc.nextLine();
// send to server
if (str != null){
try {
this.writer.write(str);
this.writer.newLine();
this.writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class ReceiveThread implements Runnable{
private BufferedReader reader;
public ReceiveThread(BufferedReader reader){
this.reader = reader;
}
#Override
public void run() {
while (true){
String res = null;
try {
res = this.reader.readLine();
if (res != null){
System.out.println("Server response: "+ res);
}
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
}
}
}
The error message is:
java.net.SocketException: Socket closed
at java.base/java.net.SocketInputStream.socketRead0(Native Method)
at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:115)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:168)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:140)
at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.base/java.io.InputStreamReader.read(InputStreamReader.java:185)
at java.base/java.io.BufferedReader.fill(BufferedReader.java:161)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:326)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:392)
at Peer$ReceiveThread.run(Peer.java:86)
at java.base/java.lang.Thread.run(Thread.java:834)
It occurs in ReceiveThread in the Peer class.
Any bits of help is appreciated. Thank you!
Yige
Since you are using a try-with-resources, the socket is automatically closed immediately after you start t1 and t2.
You can think of
try (Socket socket = new Socket(hostname, port)){
// [...]
t1.start();
t2.start();
}
//
like this:
Socket socket;
try {
socket = new Socket(hostname, port)
// [...]
t1.start();
t2.start();
} catch (/* [...] */) {
} finally {
if (socket != null) {
socket.close(); // <- here the socket is closed
}
}
And since the thread is running in the background, t1.start() does not wait until thread-1 has finished -> the socket is closed.
Without try-with-resources:
public class Peer {
private Socket socket;
// [...]
public Peer(String hostname, int port) {
// [...]
try {
this.socket = new Socket(hostname, port);
// [...]
} catch (UnknownHostException | IOException ex) {
ex.printStackTrace();
System.exit(-1);
}
}
// Call this method when your program exits
public void close() {
if (this.socket != null) {
this.socket.close();
}
}
}

java.net.SocketException: Socket is closed between Socket.accept() and Socket.getInputStream()

I'm trying to create a client/server connection and am still quite new to java as well. So the error I am getting tells me that the socket is closed. Following some work, I've managed to write the given code below. I do believe there is something wrong with the way I pass the socket to the connection class, if I had to guess, that causes the socket object to possibly be closed?
I've tried adding waits just in case the server thread hadn't been executed but that didn't seem to affect anything. Maybe I should launch the server with its own launcher in its own command prompt, but I thouht this should work just fine to test the client and server.
I can't seem to find out why my socket is closed before I send my message. Any insights would be greatly appreciated!
Thanks!
Error
java.net.SocketException: Socket is closed
at java.net.Socket.getInputSTream(Unknown Source)
at Connection.run(Connection.java:17)
Server.java
//main calling snippet.
import java.lang.Thread;
public class Server {
public static void main(String[] args) {
if(args.length != 1) {
System.err.println("Usage: java Server <port number>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
Thread server = new KServer(port);
server.start();
//added waits just to make sure the thread was executed?
//thinking this might be my problem
long t = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < t) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
KClient client = new KClient("127.0.0.1",port);
while (!(client.openConn())) {
System.out.println("Failed to connect. Retrying...");
}
client.send("Hello World");
client.closeConn();
}
}
KServer.java
//the actual server class that manages listening and threading the sockets
import java.net.*;
import java.io.*;
public class KServer extends Thread {
private int port;
private ServerSocket sSock;
public KServer(int thisPort) {
port = thisPort;
try {
sSock = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while(true) {
try (Socket cSock = sSock.accept();) {
Thread con = new Connection(cSock);
con.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Connection.java
//Manages sending and receiving messages
import java.net.Socket;
import java.io.*;
public class Connection extends Thread {
Socket socket;
public Connection(Socket s) {
socket = s;
}
public void run() {
String msg;
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while((msg = in.readLine()) != null) {
System.out.println(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
KClient.java
//manages the clients connection life to the server
import java.net.*;
import java.io.*;
public class KClient {
private Socket sock;
private String dest;
private int port;
private OutputStreamWriter out;
public KClient(String dst,int prt) {
dest = dst;
port = prt;
}
public boolean openConn() {
try {
sock = new Socket(dest,port);
out = new OutputStreamWriter(sock.getOutputStream(),"ISO-8859-1");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public void send(String msg) {
try {
out.write(msg);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void closeConn() {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Don't use try-with-resources to accept the socket. It wil close the accepted socket, which needs to stay open so the handling thread can use it. The handling thread is responsible for closing it.

How to write A ServerSocket which accept multiple clicent Socket?

I am working on Socket programming. I have build such a server which should accept multiple Clients. Here I have particular num of clients , clients keeps on sending msg to Server every 10sec , Server has to process it.The problem I am having is I am unable to connect multiple Server and here a single client is a continuous running programm in while(true) So if one client Sends a request another client can not connect . Here is my Program.
Server
public class SimpleServer extends Thread {
private ServerSocket serverSocket = null;
private Socket s1 = null;
SimpleServer() {
try {
serverSocket = new ServerSocket(1231);
this.start();
} catch (IOException ex) {
System.out.println("Exception on new ServerSocket: " + ex);
}
}
public void run() {
while (true) {
try {
System.out.println("Waiting for connect to client");
s1 = serverSocket.accept();
System.out.println("Connection received from " + s1.getInetAddress().getHostName());
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = dis.readUTF();
System.out.println(st);
s1In.close();
dis.close();
s1.close();
// throw new ArithmeticException();
} catch (IOException ex) {
Logger.getLogger(SimpleServer.class.getName()).log(Level.SEVERE, null, ex);
}
catch (Exception e) {
System.out.println("Exceptiopn: "+e);
}
}
}
public static void main(String args[]) throws IOException {
new SimpleServer();
}
}
Server is working fine but I am not able to write Client program which shoud run in while(true) loop for sending msg to Server and allow other client also connect to Server.
but for a single client I write like this ,
public class SimClient extends Thread {
private Socket s1 = null;
SimClient() {
//this.start();
}
public void run() {
int i=0;
try {
s1 = new Socket("localhost", 1231);
} catch (IOException ex) {
Logger.getLogger(SimClient.class.getName()).log(Level.SEVERE, null, ex);
}
// while (i<10) {
try {
// Open your connection to a server, at port dfg1231
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(s1out);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Data from Client:");
String s = br.readLine();
dos.writeUTF(s);
dos.flush();
s1out.close();
dos.close();
// s1.close();
i++;
} catch (IOException ex) {
//ex.printStackTrace();
System.out.println("Exception in While: "+ex.getMessage());
}
//}
}
public static void main(String args[]) throws IOException {
SimClient s= new SimClient();
s.start();
}
}
So can any one help me to write client program. its a great help for me.
just as you have a Thread for the ServerSocket, you need to create a Thread for every Socket returned by serverSocket.accept() , then it loops back around immediately to block and wait to accept another Socket. Make a class called SocketHander which extends Thread and accepts a Socket in the constructor.
public class SocketHandler extends Thread {
private Socket socket;
public SocketHandler(Socket socket) {
this.socket = socket;
}
public void run() {
// use the socket here
}
}
and back in the ServerSocket handler...
for (;;) {
SocketHandler socketHander = new SocketHandler(serverSocket.accept());
socketHander.start();
}
It is generally a good idea to use a Fixed Size Thread Pool because creating Threads in a ad-hoc manner may cause the Server to run out of Threads if the requests are high.
public class SimpleServer extends Thread {
private ServerSocket serverSocket = null;
private static ExecutorService executor = Executors.newFixedThreadPool(100);
SimpleServer() {
try {
serverSocket = new ServerSocket(1231);
this.start();
} catch (IOException ex) {
System.out.println("Exception on new ServerSocket: " + ex);
}
}
public void run() {
while (true) {
try {
System.out.println("Waiting for connect to client");
final Socket s1 = serverSocket.accept();
executor.execute(new Runnable() {
public void run() {
try {
System.out.println("Connection received from " + s1.getInetAddress().getHostName());
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = dis.readUTF();
System.out.println(st);
s1In.close();
dis.close();
s1.close();
} catch(Exception e) {
System.out.println("Exceptiopn: "+e);
}
// throw new ArithmeticException();
}});
} catch (IOException ex) {
Logger.getLogger(SimpleServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception e) {
System.out.println("Exceptiopn: "+e);
}
}
}
public static void main(String args[]) throws IOException {
new SimpleServer();
}
}

Socket writing not responding [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I made a simple application to connect a server with a client in java
It does not work
I use new Socket("localhost", 4444); for the client
and new ServerSocket(4444); for the server
Client:
http://www.hastebin.com/siqamonebu.coffee
Server:
http://www.hastebin.com/rivebetani.avrasm
I posted the code on hastebin because its to big to post here
I have no idea what part is broken but the server never receives the message you say
ChatServer - broadcasts to all connected clients
In one command prompt: java ChartServer
In another: java ChatClient localhost (or the ip address of where the server is running)
And another: java ChatClient localhost (or the ip address of where the server is running)
Start chatting in the client windows.
Server like this...
// xagyg wrote this, but you can copy it
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
public static List list = new ArrayList();
public static void main(String[] args) throws Exception {
ServerSocket svr = new ServerSocket(4444);
System.out.println("Chat Server started!");
while (true) {
try {
Socket s = svr.accept();
synchronized(list) {
list.add(s);
}
new Handler(s, list).start();
}
catch (IOException e) {
// print out the error, but continue!
System.err.println(e);
}
}
}
}
class Handler extends Thread {
private Socket s;
private String ipaddress;
private List list;
Handler (Socket s, List list) throws Exception {
this.s = s;
ipaddress = s.getInetAddress().toString();
this.list = list;
}
public void run () {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String message;
//MyDialog x = (MyDialog)map.get(ipaddress.substring(1));
while ((message = reader.readLine()) != null) {
if (message.equals("quit")) {
synchronized(list) {
list.remove(s);
}
break;
}
synchronized(list) {
for (Object object: list) {
Socket socket = (Socket)object;
if (socket==s) continue;
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println(ipaddress + ": " + message);
writer.flush();
}
}
}
try { reader.close(); } catch (Exception e) {}
}
catch (Exception e) {
System.err.println(e);
}
}
}
Client like this ...
// xagyg wrote this, but you can copy it
import java.util.*;
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], 4444);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String message;
new SocketReader(in).start();
while ((message = reader.readLine())!=null) {
out.println(message);
out.flush();
if (message.equals("quit")) break;
}
in.close();
out.close();
}
}
class SocketReader extends Thread {
BufferedReader in;
public SocketReader(BufferedReader in) {
this.in = in;
}
public void run() {
String message;
try {
while ((message = in.readLine())!=null) {
System.out.println(message);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
I think it is because how you start your server, try with this structure, since you're cretaing the ServerSocket inside the run method, that could be causing a conflict:
public class ThreadSocketServer implements Runnable {
private int port;
private boolean isRunning;
private ServerSocket ss;
public ThreadSocketServer(int port, boolean initialStatus) {
this.port = port;
isRunning = initialStatus;
System.out.println("Start the server!");
try {
ss = new ServerSocket(port);
Thread threadServer = new Thread(this);
threadServer.start();
} catch (IOException e) {
System.err.println(e.getClass() + " - " + e.getMessage());
}
}
#Override
public void run() {
while (isRunning) {
try {
Socket client = ss.accept();
ObjectInputStream ois = new ObjectInputStream(
client.getInputStream());
//Process here
ois.close();
} catch (IOException e) {
System.err.println(e.getClass() + " - " + e.getMessage());
isRunning = false;
} catch (ClassNotFoundException e) {
System.err.println(e.getClass() + " - " + e.getMessage());
isRunning = false;
}
}
}
public static void main(String[] args) {
new ThreadSocketServer(1085, true);
}

Socket Issue - Only first message read

I am very new to sockets and was hoping someone could help me. I had something working but it was not sending information very quickly so i have refactored and now cannot get back to anything which works. The issue seems to be that only the first message that is published is read and then the receiver sits on client = listener.accept(); even though im pretty sure the sender is still sending messages
Can anyone see what i might be doing wrong here please?
Thanks
public class Sender {
Socket server = null;
DataInputStream inp = null;
PrintStream outp = null;
public Sender(){
server = new Socket("127.0.0.1" , 3456);
outp = new PrintStream(server.getOutputStream());
}
private void connectAndSendToServer(String message) {
outp = new PrintStream(server.getOutputStream());
outp.print(message + "\n");
outp.flush();
}
}
Receiver class
public class Receive{
public String receiveMessage(int port) {
String message= null;
ServerSocket listener = null;
Socket client = null;
try{
listener = new ServerSocket(port);
client = listener.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
return br.readLine();
}
...
finally{
try {
if(client!=null && listener!=null){
client.close();
listener.close();
}
}
catch (IOException e) {
}
}
return message;
}
}
This because a ServerSocket is used as an entry point for a normal Socket. accept() is a blocking operation that is usually done on a different thread compared to the one that receives/sends data to normal Socket. It sits there and waits for a new connection to spawn a new Socket which is then used for data.
This means that while receiving messages you should call just readLine() to read from the specific Socket. Having an accept inside the receiveMessage is wrong just because it's a different operation and it's even blocking.
Socket socket = serverSocket.accept();
ClientThread thread = new ClientThread(socket);
class ClientThread extends Thread {
Socket socket;
public void run() {
while (!closed) {
String line = reader.readLine();
...
}
}
You don't need to have a thread for every client though, but you need at least two for sure if you want to make your server accept a number of connections greater than 1.
You are not using ServerSocket correctly. You shouldn't create a new instance for every message but use it as a data member maybe and run an infinite loop to get a new client socket connection. Because you create it locally, the socket is closed since the object is no longer used and referenced (and so GC'ed), when you return from the method.
Something like (< condition met > is pseudo-code defines your condition to accept new connections):
while(< condition met >) {
try {
client = listener.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = br.readLine();
//do something with str
} finally {
//close client socket
}
}
Better approach will be to handle client socket in a different thread so the main thread is back to accept while you can do anything with the client socket in parallel.
Try this basic Chatting Server written by me. This server simply keeps running in loop and broadcast the message send by the clients to all the other clients associated with this server.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
// ///----------------------------------------Instance Variable Fields
ServerSocket ss = null;
Socket incoming = null;
// ///----------------------------------------Instance Variable Fields
// ///---------------------------------------- static Variable Fields
public static ArrayList<Socket> socList = new ArrayList<Socket>();
// ///---------------------------------------- static Variable Fields
public void go() {
try {
ss = new ServerSocket(25005);
while (true) {
incoming = ss.accept();
socList.add(incoming);
System.out.println("Incoming: " + incoming);
new Thread(new ClientHandleKaro(incoming)).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandleKaro implements Runnable {
InputStream is = null;
OutputStream os = null;
InputStreamReader isr = null;
BufferedReader br = null;
PrintWriter pw = null;
boolean isDone = false;
Socket sInThread = null;
public ClientHandleKaro(Socket sxxx) {
this.sInThread = sxxx;
}
#Override
public void run() {
if (sInThread.isConnected()) {
System.out.println("Welcamu Clienta");
System.out.println(socList);
}
try {
is = sInThread.getInputStream();
System.out.println("IS: " + is);
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
os = sInThread.getOutputStream();
pw = new PrintWriter(os, true);
String s = new String();
while ((!isDone) && (s = br.readLine()) != null) {
String[] asx = s.split("-");
System.out.println("On Console: " + s);
// pw.println(s);
Thread tx = new Thread(new ReplyKaroToClient(s,
this.sInThread));
tx.start();
if (asx[1].trim().equalsIgnoreCase("BYE")) {
System.out.println("I am inside Bye");
isDone = true;
}
}
} catch (IOException e) {
System.out.println("Thanks for Chatting.....");
} finally {
try {
Thread tiku = new Thread(new ByeByeKarDo(sInThread));
tiku.start();
try {
tiku.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Accha to hum Chalte hain !!!");
System.out.println(socList);
br.close();
pw.close();
sInThread.close();
} catch (IOException e) {
}
}
}
}
class ReplyKaroToClient implements Runnable {
public String mString;
public Socket mSocket;
public ReplyKaroToClient(String s, Socket sIn) {
this.mString = s;
this.mSocket = sIn;
}
#Override
public void run() {
for (Socket sRaW : socList) {
if (mSocket.equals(sRaW)) {
System.out.println("Mai same hun");
continue;
} else {
try {
new PrintWriter(sRaW.getOutputStream(), true)
.println(mString);
} catch (IOException e) {
System.out.println("Its in Catch");
}
}
}
}
}
class ByeByeKarDo implements Runnable {
Socket inCom;
public ByeByeKarDo(Socket si) {
this.inCom = si;
}
#Override
public void run() {
try {
new PrintWriter(inCom.getOutputStream(), true)
.println("You have Logged Out of Server... Thanks for your Visit");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Server().go();
}
}

Categories

Resources