Socket通信作为一种重要的数据交互方式,在Android开发过程也十分重要。
//TCP Socket服务端
ServerSocket serverSocket = null; try { //4567 ServerSocket端口号 serverSocket = new ServerSocket(4567); //服务端接受客户端的Socket请求 Socket socket = serverSocket.accept(); //获取输入流 InputStream inputStream = socket.getInputStream(); byte buffer[] = new byte[4*1024]; int temp = 0; //将InputStream数据读入到Buffer中 while((temp = inputStream.read(buffer)) != -1){ } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }
客户端:
try { Socket socket = new Socket("192.168.0.104", 4567); InputStream inputStream = new FileInputStream("f://file/word.txt"); OutputStream outputStream = socket.getOutputStream(); byte buffer[] = new byte[4*1024]; int temp = 0; while((temp = inputStream.read(buffer)) != -1){ outputStream.write(buffer, 0, temp); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
UDP Socket服务端:
try { DatagramSocket datagramSocket = new DatagramSocket(4567); byte data[] = new byte[4*1024]; DatagramPacket datagramPacket = new DatagramPacket(data, data.length); datagramSocket.receive(datagramPacket); } catch (Exception e) { // TODO: handle exception }
客户端:
try { DatagramSocket socket = new DatagramSocket(4567); InetAddress inetAddress = InetAddress.getByName("192.168.0.104"); String helloWorld = "helloworld"; byte[] data = helloWorld.getBytes(); DatagramPacket datagramPacket = new DatagramPacket(data, data.length, inetAddress,4567); socket.send(datagramPacket); } catch (Exception e) { // TODO: handle exception }