1. 程式人生 > >android網路HTTP和TCP

android網路HTTP和TCP

製作基於TCP的聊天室

獲取訪問許可權
要訪問網路,需要在你的配置檔案中獲取INTERNET許可權

Android客戶端

public class MainActivity extends Activity implements OnClickListener {

    EditText et;
    TextView tv;
    OutputStream os;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et = (EditText) findViewById(R.id.editText1);
        tv = (TextView) findViewById(R.id.textView1);

        findViewById(R.id.button1).setOnClickListener(this
); findViewById(R.id.button2).setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub if (v.getId() == R.id.button1) { String info = et.getText().toString(); // 向textView新增內容 tv.append("me:"
+ info + "\n"); et.setText(""); // 將使用者輸入的資訊傳送給伺服器 DataOutputStream dos = new DataOutputStream(os); try { dos.writeUTF(info); } catch (IOException e) { e.printStackTrace(); } } else if (v.getId() == R.id.button2) { // 登入聊天室
new AsyncTask<Void, String, Void>() { @Override protected Void doInBackground(Void... params) { // TODO Auto-generated method stub try { boolean isRun = true; Socket socket = new Socket("192.168.0.103", 8989); publishProgress("聯網成功", "1"); os = socket.getOutputStream(); // 接收伺服器資料 InputStream is = socket.getInputStream(); DataInputStream dis = new DataInputStream(is); while (isRun) { // 阻塞 String info = dis.readUTF(); publishProgress(info); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); if (values.length == 2) { Toast.makeText(MainActivity.this, "聯網成", Toast.LENGTH_SHORT).show(); } else { tv.append(values[0] + "\n"); } } }.execute(); } } }

activity_main.

JAVA伺服器端
public class Test {

    public static  ArrayList<Socket> listSocket = new ArrayList<Socket>();
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        boolean isRun = true;


        try {
            System.out.println(InetAddress.getLocalHost());
            ServerSocket server = new ServerSocket(8989);
            //客戶端的身份編號
            int count = 0;

            while(isRun){
                System.out.println("監聽是否有客戶端連線...");
                Socket socket = server.accept();
                count++;
                System.out.println("客戶端" + count + "已連線");
                listSocket.add(socket);
                //啟動一個新執行緒
                new MyThread(socket, "clinet_"+count).start();
            }

            server.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
public class MyThread extends Thread {

    Socket socket;
    String name;


    public MyThread(Socket socket, String name) {
        // TODO Auto-generated constructor stub
        this.socket = socket;
        this.name = name;
    }

    public void run() {
        super.run();

        // TODO Auto-generated method stub
        boolean isRun = true;
        try {
            //
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);


            while(isRun){
                //接收資料
                String info = dis.readUTF();

                System.out.println(name + ":" + info);

                //傳送資料 (向所有的客戶端發資料,除了自己)
                for (int i = 0; i < Test.listSocket.size(); i++) {
                    Socket clientSocket = Test.listSocket.get(i);
                    if(!clientSocket.equals(this.socket)){
                        OutputStream os = clientSocket.getOutputStream();
                        DataOutputStream dos = new DataOutputStream(os);
                        dos.writeUTF(name + ":" + info);
                    }
                }

            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }
}

基於Http的網路請求

什麼是http
超文字傳輸協議(HyperText Transfer Protocol – HTTP)是一個設計來使客戶端和伺服器順利進行通訊的協議。HTTP在客戶端和伺服器之間以request-response protocol(請求-回覆協議)工作。
http請求型別
get請求:從指定的伺服器中獲取資料
post請求:提交資料給指定的伺服器處理

public class MainActivity extends Activity implements OnClickListener {
    ImageView iv;
    ProgressBar pb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv=(ImageView) findViewById(R.id.imageView1);
        pb=(ProgressBar) findViewById(R.id.progressBar1);
        findViewById(R.id.button1).setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        new AsyncTask<String, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(String... params) {
                try {
                    //建立URL物件
                    URL url=new URL(params[0]);
                    //開啟超連結,得到物件
                    HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                    //獲取位元組流
                    InputStream is=conn.getInputStream();
                    //將位元組流的資料讀出來生成點陣圖物件
                    Bitmap bitmap=BitmapFactory.decodeStream(is);
                    return bitmap;
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);
                pb.setVisibility(View.INVISIBLE);
                iv.setVisibility(View.VISIBLE);
                iv.setImageBitmap(result);
            };
    }.execute("http://www.nowamagic.net/librarys/images/random/rand_11.jpg");
    }
}