【Android】TCP/IP协议和UDP协议

客户端发送请求连接SYN报文(SYN=1,seq=client_isn)
服务端在接受连接后返回ACK报文,并为这次链接分配资源(SYN=1,seq=client_isn,ack = client_isn+1)
客户端接收到报文后再次返回ACK报文给服务端(确认收到报文),服务端接受到报文后,就成功建立了TCP连接(SYN=0,seq=client_isn+0,ack = client_isn+1)

关闭连接

  1. 客户端发起中断连接请求,向服务端发送Fin报文
  2. 服务端接受到报文后,返回一个Ack,客户端收到的ACK报文后进入Fin等待状态
  3. 等待服务端确认事情做完了之后就发送一个Fin报文,通知说服务器完成了数据,可以关闭了
  4. 客户端收到后向服务器发送一个Ack后再次进入等待状态,服务端接收到Ack后就

可以直接关闭了,客户端在等待30s后就会关闭

【Android】TCP/IP协议和UDP协议_第1张图片
0_131271823564Rx.gif
【Android】TCP/IP协议和UDP协议_第2张图片
0_1312718352k8l6.gif
【Android】TCP/IP协议和UDP协议_第3张图片
0_1312718564tZXD.gif
【Android】TCP/IP协议和UDP协议_第4张图片
0_1312719833030b.gif
【Android】TCP/IP协议和UDP协议_第5张图片
0_1312719804oSkK.gif


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() {
        @Override
        protected String doInBackground(String... params) {
            StringBuffer sb = new StringBuffer();
            try {
                //通过URl获取到访问地址
                URL url = new URL(params[0]);
                //获取到链接的Connection资源
                URLConnection connection = url.openConnection();
                //通过connection获取数据流,并将获得的字节流数据转成字符流
                InputStream ins = connection.getInputStream();
                InputStreamReader insReader = new InputStreamReader(ins);
                //将获得的字符流数据转化成更容易处理的字符输入流
                BufferedReader br = new BufferedReader(insReader);
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    sb.append(line);
                }
                //最后关闭流处理
                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() {
        @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获取数据流,并将获得的字节流数据转成字符流
                InputStream ins = connection.getInputStream();
                InputStreamReader insReader = new InputStreamReader(ins);
                //将获得的字符流数据转化成更容易处理的字符输入流
                BufferedReader br = new BufferedReader(insReader);
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    sb.append(line);
                }
                //最后关闭流处理
                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() {
        @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() {
        @Override
        protected String doInBackground(String... params) {
            try {
                String urlString = params[0];
                HttpPost post = new HttpPost(urlString);
                List values = new ArrayList();
                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服务端
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
}


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();
    }
    }
    }

你可能感兴趣的:(【Android】TCP/IP协议和UDP协议)