System.out.println("the socket could not be opened "); } catch(IOException ioE){
System.out.println("I/O error occurs "); }
} }接收 import java.net.*; import java.io.IOException;public class UDPrecv {
public static void main(String[] args) {
while(true) { try { DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp); String msg = new String(dp.getData(),0,dp.getLength()); System.out.println( msg + " From :"+dp.getAddress().getHostAddress() + " Port :"+ dp.getPort() ); ds.close();
if (msg.equals("bye")) break; } catch(SocketException sException){
System.out.println("the socket could not be opened "); } catch(IOException ioE){
System.out.println("I/O error occurs "); } } } }运行: 1) 启动接收 F:\>java UDPrecv Hello World! From :127.0.0.1 Port :2274 bye From :127.0.0.1 Port :2285F:\>java UDPrecv 你好 茜儿! Hello X From :127.0.0.1 Port :2405 bye From :127.0.0.1 Port :2410F:\>2) 启动发送 F:\>java UDPsendF:\>java UDPsend byeF:\>输入bye 将退出监听
import java.net.*;
import java.io.IOException;public class UDPsend { public static void main(String[] args){
try{
DatagramSocket ds = new DatagramSocket();
String data = null ;
try{
data = args[0];
}catch(ArrayIndexOutOfBoundsException e)
{
data = "你好 茜儿!\nHello XiEr !";
}
DatagramPacket dp = new DatagramPacket(data.getBytes(),data.length(),InetAddress.getByName("127.0.0.1"),3000);
ds.send(dp);
ds.close();
}
catch(SocketException sException){
System.out.println("the socket could not be opened ");
}
catch(IOException ioE){
System.out.println("I/O error occurs ");
}
}
}接收
import java.net.*;
import java.io.IOException;public class UDPrecv {
public static void main(String[] args) {
while(true)
{
try {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
String msg = new String(dp.getData(),0,dp.getLength());
System.out.println( msg + " From :"+dp.getAddress().getHostAddress() + " Port :"+
dp.getPort() );
ds.close();
if (msg.equals("bye"))
break;
}
catch(SocketException sException){
System.out.println("the socket could not be opened ");
}
catch(IOException ioE){
System.out.println("I/O error occurs ");
}
}
}
}运行:
1) 启动接收
F:\>java UDPrecv
Hello World! From :127.0.0.1 Port :2274
bye From :127.0.0.1 Port :2285F:\>java UDPrecv
你好 茜儿!
Hello X From :127.0.0.1 Port :2405
bye From :127.0.0.1 Port :2410F:\>2) 启动发送
F:\>java UDPsendF:\>java UDPsend byeF:\>输入bye 将退出监听