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);
}
}
答案 0 :(得分:0)
如果您希望能够向他们发送某些内容,您必须(至少)维护已连接客户的列表。
不要重新发明轮子,在这里偷看你需要的东西: Building a Java chat server
请参见第22页,课程Server
,方法sendToAll(String message)