我已经创建了一个聊天服务器,我的客户端可以连接到该客户端但客户端不会收到对方发送的消息。这是完成这一切的代码。发送和接收并设置输出流。将数据发送到套接字列表中的套接字
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存储到这个列表中。如果有更好的方法,请让我知道。