如何Socket實現(xiàn)多個客戶端相互通信(圖文無關(guān))
public class ServerThread extends Thread {
// 和本線程相關(guān)的Socket
Socket socket = null;
public ServerThread(Socket socket) {
this.socket = socket;
}
//線程執(zhí)行的操作,響應(yīng)客戶端的請求
public void run(){
InputStream is=null;
InputStreamReader isr=null;
BufferedReader br=null;
OutputStream os=null;
PrintWriter pw=null;
try {
//獲取輸入流,并讀取客戶端信息
is = socket.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String info=null;
while((info=br.readLine())!=null){//循環(huán)讀取客戶端的信息
System.out.println("我是服務(wù)器,客戶端說:"+info);
}
socket.shutdownInput();//關(guān)閉輸入流
//獲取輸出流,響應(yīng)客戶端的請求
os = socket.getOutputStream();
pw = new PrintWriter(os);
pw.write("歡迎您!");
pw.flush();//調(diào)用flush()方法將緩沖輸出
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//關(guān)閉資源
try {
if(pw!=null)
pw.close();
if(os!=null)
os.close();
if(br!=null)
br.close();
if(isr!=null)
isr.close();
if(is!=null)
is.close();
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2016-07-02
所謂的多客戶端相互通信,其實就是服務(wù)端在中間負(fù)責(zé)轉(zhuǎn)發(fā)多個客戶端的消息而已。