標籤:
1.服務端開發
建立一個Java程式
public class MyServer {// 定義儲存所有的Socket,與用戶端建立串連得到一個Socketpublic static List<Socket> socketList = new ArrayList<Socket>();public static void main(String[] args) throws IOException {ServerSocket server = new ServerSocket(8888);while (true) {System.out.println("start listening port 8888");Socket socket = server.accept();System.out.println("connect succeed.");socketList.add(socket);//每當用戶端串連之後啟動一條ServerThread線程為該用戶端服務 new Thread(new MyServerRunnable(socket)).start(); }}public static class MyServerRunnable implements Runnable {// 定義當前線程處理的SocketSocket socket = null;// 該線程所處理的Socket所對應的輸入資料流BufferedReader bufferedReader = null;public MyServerRunnable(Socket socket) {this.socket = socket;try {// 將伺服器端的輸入資料流的資料放入讀Buffer中bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));} catch (Exception e) {e.printStackTrace();}}@Overridepublic void run() {String content = null;// 採用迴圈不斷的從Socket中讀取用戶端發送過來的資料while ((content = readFromClient()) != null) {// 遍曆socketList中的每一個Socket,將讀取的內容向每個Socket發送一次for (Socket socket : MyServer.socketList) {OutputStream outputStream;try {outputStream = socket.getOutputStream();outputStream.write(("Server: " + content + "\n").getBytes("utf-8"));} catch (IOException e) {e.printStackTrace();}}}}// 定義讀取用戶端的資訊public String readFromClient() {try {return bufferedReader.readLine();} catch (Exception e) {e.printStackTrace();}return null;}}}
2. 建立一個Android程式
1) Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity" > <TextView android:id="@+id/show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="顯示接收到伺服器端資料" /> <Button android:id="@+id/send" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="發送資料到伺服器端" /></LinearLayout>
2)ClientThread類
package com.example.testclient;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.Socket;import java.net.SocketTimeoutException;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.util.Log;public class ClientThread implements Runnable {private Socket s;// 定義向UI線程發送訊息的Handler對象Handler handler;// 定義接收UI線程的Handler對象Handler revHandler;// 該線程處理Socket所對用的輸入輸出資料流BufferedReader br = null;OutputStream os = null;public ClientThread(Handler handler) {this.handler = handler;}@Overridepublic void run() {s = new Socket();Log.d("111111111111", "@@@@@@@@@@@@@@@@@@@@");try { //192.168.0.26 為PC IP地址。
s.connect(new InetSocketAddress("192.168.0.26", 8888), 5000);Log.d("111111111111", "$$");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);Log.d("111111111111", content);}} catch (IOException io) {io.printStackTrace();}}}.start();// 為當前線程初始化LooperLooper.prepare();// 建立revHandler對象revHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {// 接收到UI線程的中使用者輸入的資料if (msg.what == 0x345) {// 將使用者在文字框輸入的內容寫入網路try {os.write(("Client" + msg.obj.toString() + "\r\n").getBytes("utf-8"));} catch (Exception e) {e.printStackTrace();}}}};// 啟動LooperLooper.loop();} catch (SocketTimeoutException e) {Message msg = new Message();msg.what = 0x123;msg.obj = "網路連接逾時!";handler.sendMessage(msg);}catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
3. MainActivity
public class MainActivity extends Activity {Handler handler;// 定義與伺服器通訊的子線程ClientThread clientThread;TextView show;Button send;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);show = (TextView) this.findViewById(R.id.show);send = (Button) this.findViewById(R.id.send);send.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubtry {// 當使用者按下按鈕之後,將使用者輸入的資料封裝成Message// 然後發送給子線程HandlerMessage msg = new Message();msg.what = 0x345;msg.obj = "Android 網路編程--Socket通訊編程";clientThread.revHandler.sendMessage(msg);} catch (Exception e) {e.printStackTrace();}}});handler = new Handler() {@Overridepublic void handleMessage(Message msg) {// 如果訊息來自子線程if (msg.what == 0x123) {// 將讀取的內容追加顯示在文字框中show.append("\n" + msg.obj.toString());show.setTextSize(50);}}};clientThread = new ClientThread(handler);// 用戶端啟動ClientThread線程建立網路連接、讀取來自伺服器的資料new Thread(clientThread).start();}}
參考:http://blog.csdn.net/thanksgining/article/details/43561053
Android 網路編程 Socket