美文网首页Android开发Android开发经验谈程序员
Socket建立通信获取消息以及发送

Socket建立通信获取消息以及发送

作者: 阴天吃鱼 | 来源:发表于2018-06-15 17:29 被阅读19次

    公司要做一个视频采集socket通信的项目,第三方服务端已经提供好了服务,让我们对接,但是目前ui还没有,所以就暂时先自己写个小demo测试一下数据连接。


    22.png
    • 先看下布局吧,很直观。
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="socket.hdsx.com.socketdemo.MainActivity">
    
        <EditText
            android:id="@+id/port"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="端口号"
            android:text="5500" />
    
        <Button
            android:id="@+id/btn_connect"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/port"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="50dp"
            android:text="建立连接!" />
    
        <Button
            android:id="@+id/btn_receiver"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn_connect"
            android:layout_centerHorizontal="true"
            android:text="接收数据!" />
    
        <Button
            android:id="@+id/btn_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn_receiver"
            android:layout_centerHorizontal="true"
            android:text="发送数据!" />
    
    
        <Button
            android:id="@+id/btn_stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn_send"
            android:layout_centerHorizontal="true"
            android:text="断开连接!" />
    
    
        <TextView
            android:id="@+id/tv_content"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_alignParentBottom="true"
            android:gravity="center"
            android:text=""
            android:textSize="16sp" />
    
    </RelativeLayout>
    
    

    就是自己手动输入端口号,手动的ip没有写,第三方直接给的固定的。

    • 容我先建立Socket连接再说
    /*
                建立连接
                 */
                case R.id.btn_connect:
                    tv_content.setText("");
    
                    String port = this.port.getText().toString();
                    if (!"".equals(port)) {
                        intPort = Integer.parseInt(port);
                    } else {
                        Toast.makeText(MainActivity.this, "输入端口号", Toast.LENGTH_SHORT).show();
                        return;
                    }
    
                    mThreadPool.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                /*
                                建立请求连接
                                 */
                                socket = new Socket("192.168.43.151", intPort);
                                System.out.println(socket.isConnected());
    
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (socket.isConnected()) {
                                            tv_content.setText("建立连接成功!" + intPort);
                                        } else {
                                            tv_content.setText("建立连接失败!" + intPort);
                                        }
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    break;
    
    
     private ExecutorService mThreadPool;//这就是个线程池管理
     mThreadPool = Executors.newCachedThreadPool();
    
    • 通信建立成功了, 让我先发送个参数数据再说
     case R.id.btn_send:
                    sendMessageToServer();
                    break;
    
      /*
        发送数据给服务端
         */
        private void sendMessageToServer() {
            long l = System.currentTimeMillis();
            final JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("msgType", "");
                jsonObject.put("msgValue", "");
                jsonObject.put("msgTime", l + "");
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        os = socket.getOutputStream();
                        os.write((jsonObject.toString() + "/n").getBytes("utf-8"));
                        // 数据的结尾加上换行符才可让服务器端的readline()停止阻塞
                        os.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                }
            }).start();
        }
    
    

    参数就是上面的, 这都很直观的说。

    发送消息之后,接下来就是处理返回的数据。注意这返回的数据格式很多,自行选择解析

    • 处理返回的数据
          /*
                    获取数据
                     */
                case R.id.btn_receiver:
                    tv_content.setText("");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                is = socket.getInputStream();
    //                            isr = new InputStreamReader(is);
    //                            br = new BufferedReader(isr);
    
                                DataInputStream input = new DataInputStream(is);
                                byte[] b = new byte[1024];
    
                                int len = 0;
                                String response = "";
                                while (true) {
                                    len = input.read(b);
                                    response = new String(b, 0, len);
                                    Log.e("datadadata", response);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
    
                    break;
    

    简单豪爽的转换成了string,我管你是什么。哈哈

    • 最后就是断开连接
         case R.id.btn_stop:
                    dissConnection();
                    break;
    
     /*
        断开 连接
         */
        private void dissConnection() {
            try {
                // 断开 客户端发送到服务器 的连接,即关闭输出流对象OutputStream
                os.close();
                // 断开 服务器发送到客户端 的连接,即关闭输入流读取器对象BufferedReader
                br.close();
    
                // 最终关闭整个Socket连接
                socket.close();
    
                // 判断客户端和服务器是否已经断开连接
                System.out.println(socket.isConnected());
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    hhh.png

    以上就是个简单的小demo,如果你需要可以参考参考。有关你们项目上的需求还要自己去完善,包括建立失败之后继续进行连接,接收到的是个流进行视频播放阿什么的。

    放个源码地址:https://github.com/BINBINXIAO/scoketd/tree/master

    相关文章

      网友评论

      • 森木_林木子:如何保持长链接呢,心跳包丢了吧,以及你如何判断自己已经将服务端的数据读取完毕了?
        阴天吃鱼:@森木_林木子 这个的话,我推荐你用netty socket框架,里面有封装好的。我这个只是测试了一下长连接以及消息的发送和接收,并没有去书写你说的。

      本文标题:Socket建立通信获取消息以及发送

      本文链接:https://www.haomeiwen.com/subject/btvmeftx.html