标签:style blog color os java io ar div log
由于要做app的UDP协议交互,所以就特地学习了下,其实也就类似于java的server和socket,下面就写了个简单的demo
服务端:
package com.test1; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; public class UpdServer { private byte[] buff = new byte[1024]; private DatagramPacket dp; private DatagramSocket ds; private InetSocketAddress socketAddress; public UpdServer(String host, int port){ socketAddress = new InetSocketAddress(host, port); try { ds = new DatagramSocket(socketAddress); } catch (SocketException e) { System.out.println("连接失败:" + e.getLocalizedMessage()); e.printStackTrace(); } System.out.println("服务器开启监听..."); } private String receive(String host, int port) { String info = ""; try{ dp = new DatagramPacket(buff, 0, buff.length); ds.receive(dp); info = new String(dp.getData(), 0, dp.getLength()); }catch (Exception e) { e.printStackTrace(); } return info; } public static void main(String[] args) { String host = "127.0.0.1"; int port = 8888; UpdServer server = new UpdServer(host, port); String info = server.receive(host, port); System.out.println(info); //发送信息到客服端 server.send(new String("你好,骚年!")); } private void send(String string) { DatagramPacket dps = new DatagramPacket(buff, 0, buff.length, dp.getAddress(), dp.getPort()); dps.setData(string.getBytes()); try { ds.send(dps); } catch (IOException e) { e.printStackTrace(); } } }
客户端:
package com.test1; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class UpdClient { private byte[] buff = new byte[1024]; private DatagramPacket dp; private DatagramSocket ds; public UpdClient(){ try { ds = new DatagramSocket(); } catch (SocketException e) { e.printStackTrace(); } } public static void main(String[] args) { UpdClient updClient = new UpdClient(); String host = "127.0.0.1"; int port = 8888; updClient.send(host, port, new String("你好,少年!").getBytes()); //接受 String info = updClient.receive(); System.out.println(info); } private String receive() { DatagramPacket dpr = new DatagramPacket(buff, buff.length); String info = ""; try { ds.receive(dpr); info = new String(dpr.getData(), 0, dpr.getLength()); } catch (IOException e) { e.printStackTrace(); } return info; } private void send(String host, int port, byte[] b) { try{ dp = new DatagramPacket(buff, 0, buff.length, InetAddress.getByName(host), port); dp.setData(b); ds.send(dp); }catch (Exception e) { e.printStackTrace(); } } }
标签:style blog color os java io ar div log
原文地址:http://www.cnblogs.com/tplovejava/p/UDP.html