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