给定以下代码:
Client c1 = new Client();
c1.connect("127.0.0.1",1300);
连接功能:
public void connect(String serverName, int port)
{
try {
Socket socket = new Socket(serverName,port);
connection = new ConnectionProxy(socket);
connection.start();
}
catch(IOException e)
{
e.printStackTrace();
}
}
(ConnectionProxy
类扩展Thread
):
public class ConnectionProxy extends Thread {
private Socket socket;
private InputStream is;
private OutputStream os;
private StringConsumer client;
public ConnectionProxy(Socket socket)
{
this.socket = socket;
try {
is = socket.getInputStream();
os = socket.getOutputStream();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void run () {
DataInputStream dis = new DataInputStream(is);
DataOutputStream dos = new DataOutputStream(os);
while (socket != null)
{
try {
String msg = dis.readUTF();
System.out.println(msg);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
我正在尝试实现聊天,并且发现很难将客户端编写的消息发送给所有当前连接的客户端。
我怎么能那样做?我应该在服务器端保存每个对象(如 c1)的引用,还是应该在服务器端保存该ConnectionProxy
线程?如果没有,我该如何正确有效地实现它?
很想得到一些帮助!谢谢!