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);
}
}
问问题
1685 次
1 回答
0
如果您希望能够向他们发送一些东西,您必须(至少)维护一个已连接客户端的列表。
不要重新发明轮子,在这里看看你需要什么:构建 Java 聊天服务器
见第 22 页,类Server
,方法sendToAll(String message)
祝你好运!
于 2011-09-16T23:36:31.470 回答