Socket实现Android客户端与服务器的通信

前言:题目要求故写一下总结。


1.什么是Socket?

网络用语叫套接字原理是基于tcp/ip 协议的一种通信手段,目前题目中要求无非就是当客户端数据异常时推送给服务器报警信息

往常接下来都是先看效果图的,由于今天回宿舍有点早,准备有点匆忙,所以演示没准备,但代码都是测试通过的,直接贴代码吧.

这里写图片描述


* 2.MainActivity主类*

public class MainActivity extends Activity {

    EditText ip;
    EditText editText;
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ip = (EditText) findViewById(R.id.ip);
        editText = (EditText) findViewById(R.id.editText);
        tv = (TextView) findViewById(R.id.tv);

        //连接按钮
        findViewById(R.id.connect).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        connect();//连接
                    }
                });
        //发送数据按钮
        findViewById(R.id.send).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                send();
            }
        });
    }
    // ------------------------------------------------------------------------------------

    Socket socket = null;
    BufferedWriter writer = null;
    BufferedReader reader = null;

    /**
     * 异步 实现socket与服务器的连接
     */
    public void connect() {

        AsyncTask<Void, String, Void> read = new AsyncTask<Void, String, Void>() {

            @Override
            protected Void doInBackground(Void... arg0) {
                try {
                    socket = new Socket(ip.getText().toString(), 40000);

                    writer = new BufferedWriter(new OutputStreamWriter(
                            socket.getOutputStream()));

                    reader = new BufferedReader(new InputStreamReader(
                            socket.getInputStream()));
                    publishProgress("@success");
                } catch (UnknownHostException e1) {
                    System.out.println(e1.toString());
                } catch (IOException e1) {
                    System.out.println(e1.toString());
                }

                try {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        publishProgress(line);
                    }
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onProgressUpdate(String... values) {

                if (values[0].equals("@success")) {
                    Toast.makeText(MainActivity.this, "连接成功",
                            Toast.LENGTH_SHORT).show();

                }
                tv.append("别人说:" + values[0] + "\n");

                super.onProgressUpdate(values);
            }

        };
        read.execute();
    }

    /**
     * socket 发送方法
     */
    private void send() {
        try {
            tv.append("我说" + editText.getText().toString() + "\n");
            writer.write(editText.getText().toString() + "\n");
            writer.flush();
            editText.setText("");

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

3.xml布局


<LinearLayout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/ip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="10.67.66.195" >
    </EditText>

    <Button
        android:id="@+id/connect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="连接" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.85" />

    <EditText
        android:id="@+id/editText"
        android:hint="发送的消息"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="send"
        android:text="发送" />

</LinearLayout>

4.总结

代码挺简单的,因为题目需求不高,所以就一个异步加载的方法实现与服务器的通信即可。

其实如果觉得麻烦,甚至还可以继续简化一些,直接把socket写在一个子线程就可以了

new Thread(){
                    public void run() {
                        try {
                            Socket socket  = new Socket("192.168.100.1",4000);
                            .......
                        } catch (UnknownHostException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    };
                }.start();

这种方法,甚至上上面异步都会牵扯如下问题:

无法程序启动后自动连接服务器、服务器未开启监听前程序启动会崩等等

具体这两种方式出现的如上问题都已解决,以及通过socket实现android客户端接收服务器端的图片等,后面慢慢总结…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

niceyoo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值