Hi could somebody help me with this code because I was trying with If statement but is no working. I am not asking to write for me code just point me at something.
The main problem is that every time somebody connect, new thread is made but when he turn off his chat box the tread stays on and is not working as should be. I mean some body make 10 connections himself and nobody else can chat.
import java.net.*;
import java.io.*;
public class myServer {
static ServerSocket server;
static Socket client;
static DataInputStream in;
static DataOutputStream out;
static clientThread t[] = new clientThread[10];
public static void main(String[] args) throws IOException {
System.out.println("Starting Server");
server = new ServerSocket(7555);
System.out.println("Started Server");
while (true) {
client = server.accept();
System.out.println("CONNECTION");
out = new DataOutputStream(client.getOutputStream());
out.writeUTF("Welcome to the chat room");
for (int i = 0; i <= 9; i++) {
if (t[i] == null) {
(t[i] = new clientThread(client, t)).start();
break;
}
}
}
}
}
class clientThread extends Thread {
DataInputStream in;
DataOutputStream out;
static String msg;
Socket client = null;
clientThread t[];
public clientThread(Socket client, clientThread[] t) {
this.client = client;
this.t = t;
}
public void run() {
try {
in = new DataInputStream(client.getInputStream());
out = new DataOutputStream(client.getOutputStream());
boolean tru = true;
while (tru) {
msg = in.readUTF();
System.out.println(msg);
for (int i = 0; i <= 9; i++)
if (t[i] != null) {
t[i].out.writeUTF(msg);
System.out.println(t[i]);
}
}
} catch (IOException e) {
}
}
}
Your problem is not that the thread stays on, but rather that you have no mechanism for marking your client threads as finished. Even though the thread has exited,
t[i]will not becomenull. It will still refer to an instance of a thread–just a “dead” thread.Here’s are two ways to fix it:
Just before your thread exits, mark
t[i] = null(whereiis the index of the current thread). Note that you’ll need to store the value ofiin each thread.clientThreadand addprivate int threadIndex;as a member variable.Modify
clientThread‘s constructor and addthreadIndexas a parameter.Right before the closing brace of
run, addUse an
Executorand submit yourclientThreads to it. Java’sExecutors will handle cleaning up threads for you.