首先写发送数据的程序,再写接收数据的程序,否则对方无法接收到数据(原因未知)
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(); }