当我启动服务器并且客户端连接到它时,我收到此错误:
Waiting for clients ...
Client connected from: Driton PC
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
我不太明白为什么会发生这种情况,因为我从互联网上一个接一个地关注并且他的例子有效而我没有
public class ChatServer {
public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>();
public static ArrayList<String> CurrentUsers = new ArrayList<String>();
public static void main(String[] args) throws IOException{
try
{
final int PORT = 444;
ServerSocket SERVER = new ServerSocket(PORT);
System.out.println("Waiting for clients...");
while(true)
{
Socket SOCK = SERVER.accept();
ConnectionArray.add(SOCK);
System.out.println("Client connected from: "+ SOCK.getLocalAddress().getHostName());
AddUserName(SOCK);
Chat_Server_Return CHAT = new Chat_Server_Return(SOCK);
Thread x = new Thread(CHAT);
x.start();
}
}
catch(Exception x){System.out.println(x);}
}
public static void AddUserName(Socket X) throws IOException
{
Scanner INPUT = new Scanner(X.getInputStream());
String UserName = INPUT.nextLine();
CurrentUsers.add(UserName);
for(int i = 1; 1 <= ChatServer.ConnectionArray.size(); i++){
Socket TEMP_SOCK = (Socket) ChatServer.ConnectionArray.get(i-1);
PrintWriter OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
OUT.println("#?!"+ CurrentUsers);
OUT.flush();
}
}
它运行for
循环两次。