我已經創建了一個聊天服務器,我的客戶端可以連接到該客戶端但客戶端不會收到對方發送的消息。這是完成這一切的代碼。發送和接收並設置輸出流。將數據發送到套接字列表中的套接字
public void run()
{
while(true)
{
for(int i = 0; i < ClientConnector.Connections.size(); i++)
{
try
{
if(Socket != null)
{
ObjectOutputStream Output = new ObjectOutputStream(Socket.getOutputStream());
ObjectInputStream Input = new ObjectInputStream(Socket.getInputStream());
whileChatting(Input, Output);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public static void sendMessage(String message, String returnedMessage, ObjectOutputStream out)
{
try
{
System.out.println("[Server] " + message);
if(!message.isEmpty())
{
out.writeObject("\247c[Server]\247d " + message);
out.flush();
System.out.println("[Chat] Sent: " + message);
}
else
{
out.writeObject(returnedMessage);
System.out.println("[Chat] Sent: " + returnedMessage);
}
out.flush();
System.out.println("[Info] Flushing remaining data to stream.");
}
catch(IOException ioException)
{
System.out.println("[Warning] Error: ioException @ sendMessage line 76.");
}
}
public static void whileChatting(ObjectInputStream input, ObjectOutputStream output) throws IOException
{
String message = "";
do
{
try
{
message = (String) input.readObject();
System.out.println(message);
sendMessage("", message, output);
}
catch(ClassNotFoundException classNotFoundException)
{
System.out.println("[Warning] Error: ClassNotFoundException @ whileChatting line 1-7.");
System.out.println("idk wtf that user sent!");
}
}while(!message.equals("/stop"));
}
我想知道。我如何讓這個人發送給所有客戶?我在套接字數組列表中保留了一個套接字列表。看起來像這樣。
public static ArrayList<Socket> Connections = new ArrayList<Socket>();
當每個客戶端連接它時,它將它的Socket存儲到這個列表中。如果有更好的方法,請讓我知道。