我制作了一个聊天服务器,我的客户可以连接到该服务器,但客户没有收到对方发送的消息。这是完成这一切的代码。发送和接收以及设置输出流。
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 存储在这个列表中。如果有更好的方法可以做到这一点,请告诉我。