服务器端代码:
try {
ServerSocket socket=new ServerSocket(8008);
Socket client=socket.accept();
PrintStream out=new PrintStream(client.getOutputStream());
BufferedReader reader=new BufferedReader(new InputStreamReader(client.getInputStream()));
StringBuffer info=new StringBuffer();
info.append("接收到了来自客户端的消息");
info.append(reader.readLine());
out.print(info);
out.close();
reader.close();
client.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
客户端代码
try {
Socket client=new Socket("10.0.2.2",8008);
PrintStream out=new PrintStream(client.getOutputStream());
BufferedReader buf=new BufferedReader(new InputStreamReader(client.getInputStream()));
out.print("message from client");
out.close();
buf.close();
client.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
最后别忘了配置权限
<uses-permission android:name="android.permission.INTERNET"/>