我已经建立了一个聊天服务器,我的客户可以连接到该服务器,但客户端没有收到对方发送的消息。这是完成所有工作的代码。发送和接收并设置输出流。
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存储在此列表中。如果有更好的方法,请告诉我。
答案 0 :(得分:0)
如果这些是远程客户端,那么MulticastSocket可能会成功。如果这些是本地客户端,那么像HornetQ这样的发布/订阅消息传递服务将起作用(客户端订阅消息队列,HornetQ负责路由)。
答案 1 :(得分:0)
当你不使用迭代变量时,我没有看到循环的意义。当然你应该发送到ClientConnector.Connections.get(i)
?
此处的另一个问题是您在每次迭代时都会创建一个新的ObjectInputStream
和ObjectOutputStream
。那不行。在每个插槽的生命周期内,每个插槽必须使用相同的一对流。