Android中Socket通信案例
以下这个案例是基于TCP/UDP协议的。
服务端实现代码
基于TCP的服务端协议
// 声明一个ServerSocket对象 ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(4567); Socket socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream(); } catch (Exception e) { // TODO: handle exception }
基于UDP的服务端协议
try { DatagramSocket socket = new DatagramSocket(4567); byte[] bytes = new byte[1024]; DatagramPacket packet = new DatagramPacket(bytes, bytes.length); socket.receive(packet); } catch (Exception e) { // TODO: handle exception }
客户端实现代码
基于TCP协议的客户端
publicvoid run() {
// TODO Auto-generated method stub try { Socket socket = new Socket("192.168.1.110", 4567); OutputStream outputStream = socket.getOutputStream(); InputStream inputStream = new FileInputStream("f:/abc.txt"); byte[] bytes = new byte[2 * 1024]; while (true) { int temp = inputStream.read(bytes, 0, bytes.length); if (temp == -1) { break; } else { outputStream.write(bytes, 0, temp); } } outputStream.flush(); } catch (Exception e) { // TODO: handle exception } finally { } }
基于UDP协议的客户端
public void run() { // TODO Auto-generated method stub try { // 定义一个DatagramSocket对象,并设置端口号为4567 DatagramSocket socket = new DatagramSocket(4567); InetAddress address = InetAddress.getByName("192.168.1.110"); System.out.println(address); String str = "hello"; byte[] data = str.getBytes(); DatagramPacket packet = new DatagramPacket(data, 0, data.length, address, 4567); socket.send(packet); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }