花了大概两天的时间,终于把Android的Socket编程给整明白了。抽空和大家分享一下:
Socket Programming on Android
Socket 编程基础知识:
主要分服务器端编程和客户端编程。
服务器端编程步骤:
1: 创建服务器端套接字并绑定到一个端口上(0-1023是系统预留的,最好大约1024)
2: 套接字设置监听模式等待连接请求
3: 接受连接请求后进行通信
4: 返回,等待赢一个连接请求
客户端编程步骤:
1: 创建客户端套接字(指定服务器端IP地址与端口号)
2: 连接(Android 创建Socket时会自动连接)
3: 与服务器端进行通信
4: 关闭套接字
Android Socket 通信原理注意:
1: 中间的管道连接是通过InputStream/OutputStream流实现的。
2: 一旦管道建立起来可进行通信
3: 关闭管道的同时意味着关闭Socket
4: 当对同一个Socket创建重复管道时会异常
5: 通信过程中顺序很重要:服务器端首先得到输入流,然后将输入流信息输出到其各个客户端
客户端先建立连接后先写入输出流,然后再获得输入流。不然活有EOFException的异常。
下面是关于在服务器端编程的代码:
Java代码
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.ArrayList;
- /**
- *@author Andrew.Lee
- *@create 2011-6-1 下午04:45:19
- *@version 1.0
- *@see
- */
- public class Server {
- static ServerSocket aServerSocket = null; // Server Socet.
- DataInputStream aDataInput = null; // Server input Stream that to
- // receive msg from client.
- DataOutputStream aDataOutput = null; // Server output Stream that to
- static ArrayList list = new ArrayList();
- public static void main(String[] args) {
- try {
- aServerSocket = new ServerSocket(50003); // listen 8888 port.
- System.out.println("already listen 50003 port.");
- } catch (Exception e) {
- e.printStackTrace();
- }
- int num = 0;
- while (num < 10) {
- Socket aSessionSoket = null;
- try {
- aSessionSoket = aServerSocket.accept();
- MyThread thread = new Server().new MyThread(aSessionSoket);
- thread.start();
- num = list.size();
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- }
- class MyThread extends Thread {
- Socket aSessionSoket = null;
- public MyThread(Socket socket) {
- aSessionSoket = socket;
- }
- public void run() {
- try {
- aDataInput = new DataInputStream(aSessionSoket.getInputStream());
- aDataOutput = new DataOutputStream(aSessionSoket
- .getOutputStream());
- list.add(aDataOutput);
- while (true) {
- String msg = aDataInput.readUTF(); // read msg.
- if (!msg.equals("connect...")) {
- System.out.println("ip: "
- + aSessionSoket.getInetAddress());// ip.
- System.out.println("receive msg: " + msg);
- for (int i = 0; i < list.size(); i++) {
- DataOutputStream output = (DataOutputStream) list
- .get(i);
- output.writeUTF(msg + "----" + list.size());
- }
- if (msg.equals("end"))
- break;
- }
- aDataOutput.writeUTF("");
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- try {
- aDataInput.close();
- if (aDataOutput != null)
- aDataOutput.close();
- list.remove(aDataOutput);
- aSessionSoket.close();
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- }
- }
- }
注意问题:为了实现对于多个客户端的处理,使用了多线程的操作,每个线程维护一个Socket的连接与通信,新连接的Socket的管道被加入到ArrayList中。对于输出流的操作是对于所有的连接的客户端进行写数据。对于关闭了Socket的客户端管道从List中移除。
客户端编程代码:
Java代码
- package com.daisy.android.network;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.InetSocketAddress;
- import java.net.Socket;
- import java.net.SocketAddress;
- import java.net.UnknownHostException;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- /**
- *@author Andrew.Lee
- *@create 2011-5-28 下午02:26:20
- *@version 1.0
- *@see
- */
- public class SocketActivity extends Activity {
- EditText editText = null;
- Button sendButton = null;
- TextView display = null;
- Socket client = null;
- MyHandler myHandler;
- DataOutputStream dout;
- DataInputStream din;
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.clientsocket);
- editText = (EditText) findViewById(R.id.message);
- sendButton = (Button) findViewById(R.id.send);
- display = (TextView) findViewById(R.id.display);
- sendButton.setOnClickListener(listener);
- try {
- client = new Socket("192.168.0.120", 50003);
- dout = new DataOutputStream(client.getOutputStream());
- din = new DataInputStream(client.getInputStream());
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- myHandler = new MyHandler();
- MyThread m = new MyThread();
- m.start();
- }
- class MyHandler extends Handler {
- public MyHandler() {
- }
- // 子类必须重写此方法,接受数据
- @Override
- public void handleMessage(Message msg) {
- // TODO Auto-generated method stub
- Log.d("MyHandler", "handleMessage......");
- super.handleMessage(msg);
- // 此处可以更新UI
- if (client != null && client.isConnected()) {
- Log.i("handler..", "*-----*");
- try {
- dout.writeUTF("connect...");
- String message = din.readUTF();
- if (!message.equals(""))
- display.setText(display.getText().toString() + "\n"
- + "服务器发来的消息--:" + message);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- class MyThread extends Thread {
- public void run() {
- while (true) {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Message msg = new Message();
- SocketActivity.this.myHandler.sendMessage(msg);
- }
- }
- }
- OnClickListener listener = new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- String sendText = editText.getText().toString();
- try {
- // din = new DataInputStream(client.getInputStream());
- dout.writeUTF(sendText);
- /*
- * display.setText(display.getText().toString() + "\n" +
- * "服务器发来的消息:" + din.readUTF());
- */
- /*
- * display.setText(display.getText().toString() + "\n" +
- * "服务器发来的消息--:" + din.readUTF());
- */
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- };
- }
注意:为实现对于UI的间歇性刷新操作,使用到了Handler的消息机制。
附注:以上只是对Android的Socket编程的大致思路和过程,其中缺少了对于InputStream/OututStream 的异常处理,连接超时等处理。
摘自:http://duguyidao.iteye.com/blog/1069736
Android Socket编程