|
发表于 2011-10-22 17:55:53
|
显示全部楼层
Re:Q
Android客户端通过socket与服务器通信:
(1)通过IP地址和端口实例化Socket,请求连接服务器;
socket = new Socket("xxx.xxx.xxx.xxx",yyy); // 端口yyy,ip xxx
(2)获取Socket流以进行读写,并把流包装进BufferWriter或者PrintWriter
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
(3)对Socket进行读写
out.println(message);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = br.readLine();
(4)关闭打开的流
out.close();
br.close();
socket.close();
-------------------------------------------------------------------------------------------------------
客户端:
ServerSocket serverSocket = new ServerSocket(yyy);
//
ServerSocket和端口
接收请求
Socket client = serverSocket.accept();
接收消息
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(client.getOutputStream())),true);
关闭
out.close();
in.close();
client.close(); |
|