一個用戶端向伺服器發送資料,伺服器向串連的用戶端轉寄資料demo,轉寄demo
服務端代碼:
// 負責處理每個線程通訊的線程類public class ServerThread implements Runnable{// 定義當前線程所處理的SocketSocket s = null;// 該線程所處理的Socket所對應的輸入資料流BufferedReader br = null;public ServerThread(Socket s)throws IOException{this.s = s;// 初始化該Socket對應的輸入資料流br = new BufferedReader(new InputStreamReader(s.getInputStream() , "utf-8")); //②}public void run(){try{String content = null;// 採用迴圈不斷從Socket中讀取用戶端發送過來的資料while ((content = readFromClient()) != null){// 遍曆socketList中的每個Socket,// 將讀到的內容向每個Socket發送一次for (Socket s : MyServer.socketList){OutputStream os = s.getOutputStream();os.write((content + "\n").getBytes("utf-8"));}}}catch (IOException e){e.printStackTrace();}}// 定義讀取用戶端資料的方法private String readFromClient(){try{return br.readLine();}// 如果捕捉到異常,表明該Socket對應的用戶端已經關閉catch (IOException e){// 刪除該Socket。MyServer.socketList.remove(s); //①}return null;}}
public class MyServer{// 定義儲存所有Socket的ArrayListpublic static ArrayList<Socket> socketList= new ArrayList<Socket>(); public static void main(String[] args)throws IOException {ServerSocket ss = new ServerSocket(30000);while(true){// 此行代碼會阻塞,將一直等待別人的串連Socket s = ss.accept();socketList.add(s);// 每當用戶端串連後啟動一條ServerThread線程為該用戶端服務new Thread(new ServerThread(s)).start();} }}
用戶端代碼:
public class ClientThread implements Runnable{private Socket s;// 定義向UI線程發送訊息的Handler對象private Handler handler;// 定義接收UI線程的訊息的Handler對象public Handler revHandler;// 該線程所處理的Socket所對應的輸入資料流BufferedReader br = null;OutputStream os = null;public ClientThread(Handler handler){this.handler = handler;}public void run(){try{s = new Socket("192.168.1.88", 30000);br = new BufferedReader(new InputStreamReader(s.getInputStream()));os = s.getOutputStream();// 啟動一條子線程來讀取伺服器響應的資料new Thread(){@Overridepublic void run(){String content = null;// 不斷讀取Socket輸入資料流中的內容。try{while ((content = br.readLine()) != null){// 每當讀到來自伺服器的資料之後,發送訊息通知程式介面顯示該資料Message msg = new Message();msg.what = 0x123;msg.obj = content;handler.sendMessage(msg);}}catch (IOException e){e.printStackTrace();}}}.start();// 為當前線程初始化LooperLooper.prepare();// 建立revHandler對象revHandler = new Handler(){@Overridepublic void handleMessage(Message msg){// 接收到UI線程中使用者輸入的資料if (msg.what == 0x345){// 將使用者在文字框內輸入的內容寫入網路try{os.write((msg.obj.toString() + "\r\n").getBytes("utf-8"));}catch (Exception e){e.printStackTrace();}}}};// 啟動LooperLooper.loop();}catch (SocketTimeoutException e1){System.out.println("網路連接逾時!!");}catch (Exception e){e.printStackTrace();}}}
public class MultiThreadClient extends Activity{// 定義介面上的兩個文字框EditText input;TextView show;// 定義介面上的一個按鈕Button send;Handler handler;// 定義與伺服器通訊的子線程ClientThread clientThread;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);input = (EditText) findViewById(R.id.input);send = (Button) findViewById(R.id.send);show = (TextView) findViewById(R.id.show);handler = new Handler() //①{@Overridepublic void handleMessage(Message msg){// 如果訊息來自於子線程if (msg.what == 0x123){// 將讀取的內容追加顯示在文字框中show.append("\n" + msg.obj.toString());}}};clientThread = new ClientThread(handler);// 用戶端啟動ClientThread線程建立網路連接、讀取來自伺服器的資料new Thread(clientThread).start(); //①send.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){try{// 當使用者按下發送按鈕後,將使用者輸入的資料封裝成Message,// 然後發送給子線程的HandlerMessage msg = new Message();msg.what = 0x345;msg.obj = input.getText().toString();clientThread.revHandler.sendMessage(msg);// 清空input文字框input.setText("");}catch (Exception e){e.printStackTrace();}}});}}