分类: Android平台
2014-05-30 11:32:01
PC: Java Server
Android:Java Client
Java Server 源代码:
java代码:
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地址。
public static final String SERVERIP = "192.168.0.149";
public static final int SERVERPORT = 51706;
应用之前所指定的IP和Port创建一个ServerSocket对象。
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
用于侦听和捕捉通过Socket连接的客户端。
Socket client = serverSocket.accept();
应用Socket创建BufferedReader对象,用于接收Socket Stream中的数据。
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));