【Android】TCP/IP協(xié)議和UDP協(xié)議

客戶端發(fā)送請求連接SYN報文(SYN=1,seq=client_isn)
服務(wù)端在接受連接后返回ACK報文,并為這次鏈接分配資源(SYN=1,seq=client_isn,ack = client_isn+1)
客戶端接收到報文后再次返回ACK報文給服務(wù)端(確認收到報文),服務(wù)端接受到報文后,就成功建立了TCP連接(SYN=0,seq=client_isn+0,ack = client_isn+1)

關(guān)閉連接

  1. 客戶端發(fā)起中斷連接請求,向服務(wù)端發(fā)送Fin報文
  2. 服務(wù)端接受到報文后,返回一個Ack,客戶端收到的ACK報文后進入Fin等待狀態(tài)
  3. 等待服務(wù)端確認事情做完了之后就發(fā)送一個Fin報文,通知說服務(wù)器完成了數(shù)據(jù),可以關(guān)閉了
  4. 客戶端收到后向服務(wù)器發(fā)送一個Ack后再次進入等待狀態(tài),服務(wù)端接收到Ack后就

可以直接關(guān)閉了,客戶端在等待30s后就會關(guān)閉

0_131271823564Rx.gif
0_1312718352k8l6.gif
0_1312718564tZXD.gif
0_1312719833030b.gif
0_1312719804oSkK.gif

<pre>
package com.marco.httpconnectionapplication;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.BasicUserPrincipal;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.;
import java.net.
;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
private TextView tvContent;

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

    tvContent = (TextView) findViewById(R.id.textView);
}

//HttpGet方式
public void onBtnGet(View view) {
    new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... params) {
            StringBuffer sb = new StringBuffer();
            try {
                //通過URl獲取到訪問地址
                URL url = new URL(params[0]);
                //獲取到鏈接的Connection資源
                URLConnection connection = url.openConnection();
                //通過connection獲取數(shù)據(jù)流,并將獲得的字節(jié)流數(shù)據(jù)轉(zhuǎn)成字符流
                InputStream ins = connection.getInputStream();
                InputStreamReader insReader = new InputStreamReader(ins);
                //將獲得的字符流數(shù)據(jù)轉(zhuǎn)化成更容易處理的字符輸入流
                BufferedReader br = new BufferedReader(insReader);
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    sb.append(line);
                }
                //最后關(guān)閉流處理
                br.close();
                insReader.close();
                ins.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (TextUtils.isEmpty(sb.toString().trim())) {
                return "result null";
            } else {
                return sb.toString();
            }
        }

        @Override
        protected void onPostExecute(String s) {
            tvContent.setText("get" + s);
        }
    }.execute("http://fanyi.youdao.com/openapi.do?keyfrom=testMarco&key=1197299496&type=data&doctype=json&version=1.1&q=good");
}


//HttpPost方式
public void onBtnPost(View view) {
    new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... params) {
            StringBuffer sb = new StringBuffer();
            try {
                //通過URl獲取到訪問地址
                URL url = new URL(params[0]);
                //獲取到鏈接的Connection資源
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");

                OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
                BufferedWriter bw = new BufferedWriter(osw);
                bw.write("keyfrom=testMarco&key=1197299496&type=data&doctype=json&version=1.1&q=good");
                bw.flush();

                //通過connection獲取數(shù)據(jù)流,并將獲得的字節(jié)流數(shù)據(jù)轉(zhuǎn)成字符流
                InputStream ins = connection.getInputStream();
                InputStreamReader insReader = new InputStreamReader(ins);
                //將獲得的字符流數(shù)據(jù)轉(zhuǎn)化成更容易處理的字符輸入流
                BufferedReader br = new BufferedReader(insReader);
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    sb.append(line);
                }
                //最后關(guān)閉流處理
                br.close();
                insReader.close();
                ins.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (TextUtils.isEmpty(sb.toString().trim())) {
                return "result null";
            } else {
                return sb.toString();
            }
        }

        @Override
        protected void onPostExecute(String s) {
            tvContent.setText("post" + s);
        }
    }.execute("http://fanyi.youdao.com/openapi.do");
}

HttpClient client;

public void onBtnClientGet(View view) {
    client = new DefaultHttpClient();
    new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... params) {
            String urlString = params[0];
            HttpGet get = new HttpGet(urlString);
            try {
                HttpResponse response = client.execute(get);
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            tvContent.setText("httpClientGet" + s);
        }
    }.execute("http://fanyi.youdao.com/openapi.do?keyfrom=testMarco&key=1197299496&type=data&doctype=json&version=1.1&q=good");
}

public void onBtnClientPost(View view) {
    client = new DefaultHttpClient();
    new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... params) {
            try {
                String urlString = params[0];
                HttpPost post = new HttpPost(urlString);
                List<NameValuePair> values = new ArrayList<NameValuePair>();
                values.add(new BasicNameValuePair("keyfrom", "testMarco"));
                values.add(new BasicNameValuePair("key", "1197299496"));
                values.add(new BasicNameValuePair("type", "data"));
                values.add(new BasicNameValuePair("doctype", "json"));
                values.add(new BasicNameValuePair("version", "1.1"));
                values.add(new BasicNameValuePair("q", "good"));

                HttpResponse response = client.execute(post);
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity);
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            tvContent.setText("httpClientPost" + s);
        }
    }.execute("http://fanyi.youdao.com/openapi.do");
}

//    TCP客戶端
public void onTCPClientStart(String ip, int port) {
    try {
        final Socket socket = new Socket(ip, port);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String line = null;
                        StringBuffer sb = new StringBuffer();
                        while ((line = reader.readLine()) != null) {
                            sb.append(line);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Socket       socket;
ServerSocket serverSocket;

//TCP服務(wù)端
public void onTCPServerStart(int port) {
    try {
        serverSocket = new ServerSocket(port);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    socket = serverSocket.accept();
                    ChatSocket chatSocket = new ChatSocket(socket);
                    chatSocket.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// UDP

// SOAP
}
</pre>

<pre>
package com.marco.httpconnectionapplication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**

  • User: KdMobiB

  • Date: 2016/9/26

  • Time: 18:12
    */
    public class ChatSocket extends Thread {
    Socket socket;

    public ChatSocket(Socket socket) {
    this.socket = socket;
    }

    @Override
    public void run() {
    super.run();
    if (isAlive()){
    while (true){
    read();
    }
    }
    }

    public void read(){
    try {
    BufferedReader reader =new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String line =null;
    StringBuffer sb = new StringBuffer();
    while ((line = reader.readLine()) != null) {
    sb.append(line);
    }
    reader.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    public void write(String out){
    try {
    socket.getOutputStream().write(out.getBytes("utf-8"));
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

</pre>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容