public class UDPReceDemo
{
public static void main(String args[]){
udpreceMethod2();
}
public static void udpreceMethod2(){
DatagramSocket ds = null;
byte[] buf = new byte[1024];
DatagramPacket packet = null;
InetAddress address = null;
String ip = null;
int port = 0;
try{
ds = new DatagramSocket(9999);
packet = new DatagramPacket(buf,buf.length);
while(true){
ds.receive(packet);
address = packet.getAddress();
ip = address.getHostAddress();
port = packet.getPort();
System.out.println(ip+port+":"+new String(packet.getData(),0,packet.getLength()));
if(new String(packet.getData(),0,packet.getLength()).equals("886"))
break;
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(ds!=null) ds.close();
}catch(Exception e){
}
}
}
public static void udpReceMethod1(){
DatagramSocket ds = null;
try{
ds = new DatagramSocket(9999);
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf,buf.length) ;
ds.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getLength()));
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(ds!=null) ds.close();
}catch(Exception e){
}
}
}
}
————————————————————————————————————————————————————————————
import java.net.*;
import java.io.*;
public class UDPSendDemo
{
public static void main(String args[]){
udpSendMethod2();
}
public static void udpSendMethod2(){
BufferedReader br = null;
DatagramSocket ds = null;
String inputLine = null;
DatagramPacket packet = null;
try{
InetAddress address = InetAddress.getLocalHost();
br = new BufferedReader(new InputStreamReader(System.in));
ds = new DatagramSocket();
while(true){
inputLine = br.readLine();
packet = new DatagramPacket(inputLine.getBytes(),inputLine.getBytes().length,address,9999);
ds.send(packet);
if("886".equals(inputLine)){
break;
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(br!=null) br.close();
if(ds!=null) ds.close();
}catch(Exception e){
}
}
}
public static void udpSendMethod1(){
DatagramSocket ds = null;
try{
ds = new DatagramSocket();
byte[] buf = "你好".getBytes();
InetAddress address = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 9999);
ds.send(packet);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(ds!=null) ds.close();
}catch(Exception e){
}
}
}
}