关闭

Android TCP通信(一)

106人阅读 评论(0) 收藏 举报

什么是Socket?
Socket是应用层与TCP/IP协议簇通讯的中间抽象层,Socket是一组接口,在设计模式中,Socket的设计就是门面模式,它把复杂的TCP/IP协议簇的内容隐藏在套接字接口后面,用户无需关心协议的实现,只需使用Socket提供的接口即可。
Socket的类型有两种,一种是面向连接的TCP应用服务,一种是面向无连接的UDP(User Data Package)应用服务。通俗的理解就是,TCP方式是打电话(连接性),UDP方式是发短信(无连接)。

Ok,以上是简单的科普,那么接下来就看下如何在Android上利用TCP/IP协议使用Socket与Server进行通讯吧!今天我们要使用的是面向连接的TCP方式。首先,在本机建立一个Java项目作为Server Client,代码如下

1.服务端

开启一个socket服务端监听一个端口。

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

public class SocketServerTest {

    private static final int SERVER_PORT = 1234;

    public static void main(String[] args) {

        System.out.println("server begin lisening port " + SERVER_PORT
                + ".............");
        try {
            ServerSocket server = new ServerSocket(SERVER_PORT);
            while (true) {
                // 循环监听客户端请求
                Socket clientSocket = server.accept();
                System.out.println("server receiving.............");

                try {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(clientSocket.getInputStream()));
                    // 从客户端监听到的信息
                    String str = reader.readLine();
                    System.out.println("server received= " + str);
                } catch (Exception e) {
                    System.out.println("server error." + e.getMessage());
                } finally {
                    clientSocket.close();
                    System.out.println("server close.");
                }
            }
        } catch (IOException e) {
            System.out.println("server error." + e.getMessage());
        }
    }
}

2.客户端

package com.lq.mypractice.activity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.lq.mypractice.R;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;


public class SocketAndrodActivity extends AppCompatActivity {
    /**
     * Called when the activity is first created.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket_androd);

        Button button = (Button) this.findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new SoketTask().execute();

            }
        });


    }

    private class SoketTask extends AsyncTask<Void, Integer, Integer> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(Void... params) {
            try {
                System.out.println("Client:Connecting");
                //IP地址和端口号(对应服务端),我这的IP是本地路由器的IP地址
                Socket socket = new Socket("192.168.205.46", 1234);
                //发送给服务端的消息
                String message = "Message from Android phone";
                try {
                    System.out.println("Client Sending: '" + message + "'");

                    //第二个参数为True则为自动flush
                    PrintWriter out = new PrintWriter(
                            new BufferedWriter(new OutputStreamWriter(
                                    socket.getOutputStream())), true);
                    out.println(message);
//                      out.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //关闭Socket
                    socket.close();
                    System.out.println("Client:Socket closed");
                }
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }
    }
}

3.测试

客户端:

05-30 11:28:46.302 18016-18802/com.lq.mypractice I/System.out: Client:Connecting
05-30 11:28:46.322 18016-18802/com.lq.mypractice I/System.out: Client Sending: 'Message from Android phone'
05-30 11:28:46.322 18016-18802/com.lq.mypractice I/System.out: Client:Socket closed

服务端:

server begin.............
server receiving.............
server received= Message from Android phone
server close.

参考链接

http://blog.csdn.net/ryantang03/article/details/8274517

1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:95531次
    • 积分:2069
    • 等级:
    • 排名:第18559名
    • 原创:109篇
    • 转载:39篇
    • 译文:0篇
    • 评论:10条
    最新评论