標籤:android socket 網路聊天室
上一節的當前的伺服器只有像用戶端發送資料的功能,並沒有從用戶端讀取資料的功能,我們這一節將進行改進:
建立一個ChatManager類:
package com.test.test;import java.util.Vector;public class ChatManager {//完成類的單例:private ChatManager(){}private static final ChatManager cm=new ChatManager();public static ChatManager getChatManager(){return cm;}//完成ChatSocket線程的管理:Vector<ChatSocket> vector=new Vector<ChatSocket>();//為當前的集合添加一個新的ChatSocket對象:public void add(ChatSocket cs){vector.add(cs);}//某一個線程可以調用下面的函數像其他用戶端發送資訊public void publish(ChatSocket cs,String out){for (int i = 0; i < vector.size(); i++) {ChatSocket csChatSocket=vector.get(i);//判斷用於當前發送的線程就不用再接收此條資訊了if(!cs.equals(csChatSocket)){csChatSocket.out(out);}}}}
修改其他類1:
package com.test.test;public class MyServerSocket {public static void main(String[] args) {new ServerListener().start();}}
2:
package com.test.test;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import javax.swing.JOptionPane;public class ServerListener extends Thread {public void run() {try {ServerSocket serverSocket=new ServerSocket(12345);while(true){Socket socket=serverSocket.accept();JOptionPane.showMessageDialog(null,"有用戶端串連到了12345連接埠!");ChatSocket cs=new ChatSocket(socket);cs.start();ChatManager.getChatManager().add(cs);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
3.
package com.test.test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.Socket;public class ChatSocket extends Thread {Socket socket;public ChatSocket(Socket s){this.socket=s;}public void out(String out){try {socket.getOutputStream().write(out.getBytes("UTF-8"));} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void run() {try {BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));String line=null;while((line=br.readLine())!=null){ChatManager.getChatManager().publish(this, line);}br.close();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
類結構如下:
此時我們進行測試,開啟三個終端,然後串連,然後輸入內容,這樣每一個用戶端都能收到別人發送的資訊:
Android--使用socket通訊建立網路聊天室2