嗨有人可以幫我用這段代碼,因爲我正在嘗試使用If語句,但沒有工作。我不是要求爲我寫代碼,而是指向我一些東西。聊天服務器。線程問題
主要問題是,每次有人連接時,都會創建新的線程,但是當他關閉聊天框時,踏板會保持打開狀態並且不能正常工作。我的意思是有些身體自己做了10個連接,沒有其他人可以聊天。
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) {
}
}
}