读书人

UDP普普通通通信方式

发布时间: 2012-11-06 14:07:00 作者: rapoo

UDP普通通信方式
UDP 客户端

public class Udpsend {public static void main(String[] args) {try {DatagramSocket ds = new DatagramSocket();String str = "hello";DatagramPacket dp = new DatagramPacket(str.getBytes(), str.getBytes().length, InetAddress.getByName("192.168.1.103"), 4001);ds.send(dp);ds.close();} catch (SocketException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

UDP 服务器端代码
public class UdpRecv {private static DatagramPacket packet;public static void main(String[] args) {try {DatagramSocket ds = new DatagramSocket(4001);byte[] buf = new byte[1024];DatagramPacket packet = new DatagramPacket(buf, buf.length);ds.receive(packet);String strRecv = new String(packet.getData(), 0, packet.getLength())+ " from "+ packet.getAddress().getHostAddress()+ ":"+ packet.getPort();System.out.println(strRecv);ds.close();} catch (SocketException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

读书人网 >软件架构设计

热点推荐