• 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协议的客户端
    public
    void 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(); } }
  • 相关阅读:
    css 网格布局简单应用
    服务器常用状态码
    js 操作数组
    下拉框 tree 基于 EasyUi
    c# 导出Excel
    select 多选 (EasyUI)
    如何提高sql查询速度
    总结JS中string、math、array的常用的方法
    php 验证邮箱 php验证手机号码 ph验证身份证
    jquery+php ajax上传多图片即时显示
  • 原文地址:https://www.cnblogs.com/yshuaiw/p/3433579.html
Copyright © 2020-2023  润新知