Android TCP、UDP客户端通信功能 Android编程实现TCP、UDP客户端通信功能示例
老码农豆豆 人气:0想了解Android编程实现TCP、UDP客户端通信功能示例的相关内容吗,老码农豆豆在本文为您仔细讲解Android TCP、UDP客户端通信功能的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,TCP,UDP,客户端,通信,下面大家一起来学习吧。
本文实例讲述了Android编程实现TCP、UDP客户端通信功能。分享给大家供大家参考,具体如下:
在进行Android开发的过程中,免不了,要开发TCP/UDP通讯的程序,下面这两段代码,分别介绍了TCP/UCP通过的一个实例:
代码一 TCP通讯:
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(); }
希望本文所述对大家Android程序设计有所帮助。
加载全部内容