标签:
socket编程UDP模式,
package com.wtd.socket.udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; public class UDPServer { public static void main(String[] args) { try { DatagramSocket sever= new DatagramSocket(9000); byte[] data= new byte[100]; DatagramPacket dPacket= new DatagramPacket(data, 0, data.length); sever.receive(dPacket); String string= new String(data, 0, data.length); byte[] data2= "hello client".getBytes(); System.out.println(dPacket.getData()); DatagramPacket dPacket2= new DatagramPacket(data2, 0, data2.length,dPacket.getSocketAddress()); sever.close(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ } } }
package com.wtd.socket.udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; public class UDPClint { public static void main(String[] args) { try { DatagramSocket clint= new DatagramSocket(); String str= "hello world"; byte[] data= str.getBytes(); DatagramPacket daPacket= new DatagramPacket(data, 0, data.length, new InetSocketAddress("127.0.0.1", 9000)); clint.send(daPacket); clint.close(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
标签:
原文地址:http://www.cnblogs.com/westward/p/5490914.html