Java chat-server Application - 向所有连接的客户端预测消息时出现问题?

时间:2011-09-11 11:29:11

标签: java multithreading sockets serversocket

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

1 个答案:

答案 0 :(得分:0)

如果您希望能够向他们发送某些内容,您必须(至少)维护已连接客户的列表。

不要重新发明轮子,在这里偷看你需要的东西: Building a Java chat server
请参见第22页,课程Server,方法sendToAll(String message)

祝你好运!