考慮下面的代碼:線程和網絡問題
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();
}
}
}
我試圖實現聊天,我發現很難發送一個客戶寫的信息到當前所有的conn受影響的客戶。
我該怎麼做?我應該在服務器端持有每個對象(如c1)的引用,還是應該在服務器端持有ConnectionProxy
線程? 如果不是,我該如何正確高效地實施?
想得到一些幫助! 謝謝!