cekong

导航

android tcp发送接收数据笔记

首先写发送数据的程序,再写接收数据的程序,否则对方无法接收到数据(原因未知)

 

try {
                tcpSocket = new Socket(Ip, Integer.parseInt(tcpPort));
                while (true) {
                    //发送数据
                    Log.e("TCP开始发送:", "hello server!");
                    OutputStream OutStream = tcpSocket.getOutputStream();
                    OutStream.write("hello server!".getBytes());
                    OutStream.flush();
                    //接收数据
                    byte[] buffer = new byte[10000];
                    InputStream inputStream = tcpSocket.getInputStream();
                    DataInputStream input = new DataInputStream(inputStream);
                    int length = input.read(buffer);
                    String Msg = new String(buffer, 0, length, "gb2312");
                    Log.e("data:", Msg);
                    System.out.println("***Msg***"+Msg);

                }
            } catch (Exception ex) {
                Log.e("TCP发送接收:", ex.toString());
                ex.printStackTrace();
            }

 

posted on 2019-08-30 10:59  cekong  阅读(2310)  评论(0编辑  收藏  举报