-1
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);
}
}
4

1 に答える 1

0

何かを送信できるようにしたい場合は、(少なくとも) 接続されたクライアントのリストを維持する必要があります。

車輪を再発明するのではなく、ここで必要なものをのぞいてみてください: Java チャット サーバーの構築
22 ページのクラスServer、メソッドを参照してください。sendToAll(String message)

幸運を!

于 2011-09-16T23:36:31.470 に答える