Java Server 源代碼:
[java]
public class TCPDesktopServer implements Runnable{
public static final String SERVERIP = "192.168.0.149";
public static final int SERVERPORT = 51706;
public void run() {
try {
System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
while (true) {
Socket client = serverSocket.accept();
System.out.println("S: Receiving...");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("S: Received: '" + str + "'");
} catch(Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} finally {
client.close();
System.out.println("S: Done.");
}
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}
public static void main (String a[]) {
Thread desktopServerThread = new Thread(new TCPDesktopServer());
desktopServerThread.start();
}
}
對上邊的源代碼做一些介紹:
指定Server監聽的端口和服務器IP地址。
[java]
public static final String SERVERIP = "192.168.0.149";
public static final int SERVERPORT = 51706;
應用之前所指定的IP和Port創建一個ServerSocket對象。
[java]
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
用於偵聽和捕捉通過Socket連接的客戶端。
[java]
Socket client = serverSocket.accept();
應用Socket創建BufferedReader對象,用於接收Socket Stream中的數據。
[java]
BufferedReader in = new BufferedReader(newInputStreamReader(client.getInputStream()));
Android Client 源代碼:
[java]
InetAddress serverAddr = InetAddress.getByName("192.168.0.149");//TCPServer.SERVERIP
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, 51706);
String message = "AndroidRes,Where is my Pig (Android)?";
try {
Log.d("TCP", "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( newOutputStreamWriter(socket.getOutputStream())),true);
out.println(message);
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
socket.close();
}
對上邊的源代碼做一些介紹:
指定Server的IP地址。
[java]
InetAddress serverAddr = InetAddress.getByName("192.168.0.149");<span style="font-family:Consolas,'Bitstream Vera Sans Mono','Courier New',Courier,monospace; color:#000000; font-size:16px; white-space:normal"> </span>
應用Server的IP和端口建立Socket對象。
[java]
Socket socket = new Socket(serverAddr, 51706);<span style="font-family:Consolas,'Bitstream Vera Sans Mono','Courier New',Courier,monospace; color:#000000; font-size:16px; white-space:normal"> </span>
根據已經建立的Socket來創建PrintWriter,將信息通過這個對象來發送給Server,其中包含了三個部分:
[java]
OutputStreamWriter
BufferedWriter
PrintWriter
[java]
PrintWriter out = new PrintWriter( new BufferedWriter( newOutputStreamWr