zoukankan      html  css  js  c++  java
  • Android 开发TCP、UdP客户端

    在进行Android开发的过程中,免不了,要开发TCP/UDP通讯的程序,下面这两段代码,分别介绍了TCP/UCP通过的一个实例:

    代码一:

    private void tcpdata() {

    try {

    Socket s = new Socket("192.168.0.25", 65500);

    // outgoing stream redirect to socket

    OutputStream out = s.getOutputStream();

    // 注意第二个参数据为true将会自动flush,否则需要需要手动操作out.flush()

    PrintWriter output = new PrintWriter(out, true);

    output.println("Hello IdeasAndroid! 伪IP为:"

    + SIMCardToIP("13512345006"));

    InputStream inputStream = s.getInputStream();

    DataInputStream input = new DataInputStream(inputStream);

    byte[] b = new byte[10000];

    int length = input.read(b);

    inputReader = new InputStreamReader(inputStream);

    String Msg = new String(b, 0, length, "gb2312");

    Toast.makeText(TcpTest.this, Msg, 1000).show();

    Log.d("Tcp Demo", "message From Server:" + Msg);

    s.close();

    } catch (UnknownHostException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    下面的代码是UDP通讯的过程:
    public String send(String msg) {
    StringBuilder sb = new StringBuilder();
    InetAddress local = null;
    try {
    local = InetAddress.getByName("192.168.0.25"); // 本机测试
    } catch (UnknownHostException e) {
    e.printStackTrace();
    }
    try {
    dSocket = new DatagramSocket(); // 注意此处要先在配置文件里设置权限,否则会抛权限不足的异常
    } catch (SocketException e) {
    e.printStackTrace();
    }
    int msg_len = msg == null ? 0 : msg.length();
    DatagramPacket dPacket = new DatagramPacket(msg.getBytes(), msg_len,
    local, SERVER_PORT);
    try {
    dSocket.send(dPacket);
    } catch (IOException e) {
    e.printStackTrace();
    }
    try {
    dSocket.receive(dPacket);
    sb.append(new String(dPacket.getData()));
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    dSocket.close();
    return sb.toString();
    }
  • 相关阅读:
    eas之排序接口
    eas中删除原来的监听事件添加新的监听事件
    eas之获取单据编码规则
    eas更改用户组织范围和业务组织范围
    ECMAScript 6 文档
    java网络编程介绍
    计算机网络-总结(三)
    Lombok包下常用注解
    计算机网络介绍(二)
    计算机网络介绍(一)
  • 原文地址:https://www.cnblogs.com/fly_binbin/p/1943488.html
Copyright © 2011-2022 走看看