Java chat- server Application - Problem in forecasting messages to all connected clients? [closed]
-
28-10-2019 - |
Question
package chatserver;
import java.net.*;
import java.io.*;
public class ChatServer implements Runnable
{
static ServerSocket server;
static Socket sc;
private static OutputStream ops;
private static InputStream ips;
private static DataOutputStream dos;
private static DataInputStream dis;
private static String conversation ="";
ChatServer() throws IOException
{
server = new ServerSocket(5000);
System.out.println("Chat Server Started .... " );
new Thread(this).start();
}
public void run()
{
try
{
while(true)
{
sc = server.accept();
ops = sc.getOutputStream();
ips = sc.getInputStream();
dos = new DataOutputStream(ops);
dis = new DataInputStream(ips);
String st = new String(dis.readUTF());
conversation = conversation + "\n"+st;
System.out.println(conversation);
send_to_all();
dos.close();
ops.close();
sc.close();
}
}
catch(IOException ie){}
}
private void send_to_all() throws IException
{
dos.writeUTF(conversation);
}
public static void main(String[] args) throws IOException
{
new ChatServer();
InetAddress sl = server.getInetAddress();
System.out.println("Address : "+sl);
}
}
Solution
You must (at least) maintain a list of connected clients if you want to be able to send them something.
Don't reinvent the wheel, peek what you need here: Building a Java chat server
See page 22, class Server
, method sendToAll(String message)
Good luck!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow