//UDPServer.java
import java.net.*; import java.io.*; import java.util.*;
public class UDPServer { static final int INPORT=1711; private byte[] buf=new byte[1000]; private DatagramPacket dp=new DatagramPacket(buf,buf.length); private DatagramSocket socket; public UDPServer(){ try{ socket=new DatagramSocket(INPORT); System.out.println("Server started!"); while(true){ socket.receive(dp); String rcvd=Dgram.toString(dp)+",from ddress:"+dp.getAddress()+ ",port:"+dp.getPort(); System.out.println(rcvd); String echoString="Echoed:"+rcvd; DatagramPacket echo=Dgram.toDatagram(echoString,dp.getAddress(),dp.getPort()); socket.send(echo); } }catch(SocketException e){ System.err.println("Can't open socket"); System.exit(1); }catch(IOException e){ System.err.println("Communication error!"); e.printStackTrace();
}
} public static void main(String[] args){ new UDPServer(); } }
//UDPClient.java
import java.lang.Thread; import java.net.*; import java.io.*;
public class UDPClient extends Thread{
private DatagramSocket s; private InetAddress hostAddress; private byte[] buf=new byte[1000]; private DatagramPacket dp=new DatagramPacket(buf,buf.length); private int id;
public UDPClient(int identifier){ id=identifier; try{ s=new DatagramSocket(); hostAddress=InetAddress.getByName("localhost"); }catch(UnknownHostException e){ System.err.println("Cannot find host"); System.exit(1); }catch(SocketException e){ System.err.println("Can't open Socket"); e.printStackTrace(); System.exit(1); } }
public void run(){ try{ for(int i=0;i<1;i++){//消息数
String outMessage="Client #"+ id+",message#"+i;
s.send(Dgram.toDatagram(outMessage,hostAddress,UDPServer.INPORT)); s.receive(dp); String rcvd="Client #"+id+",rcvd from "+ dp.getAddress()+","+ dp.getPort()+":"+ Dgram.toString(dp); System.out.println(rcvd);
} }catch(IOException e){ e.printStackTrace(); System.exit(1);
} }
public static void main(String[] args){ for (int i=0;i<1;i++)//客户数量 new UDPClient(i).start(); } }
//Dgram.java 数据报格式 import java.net.*;
public class Dgram { public static DatagramPacket toDatagram( String s,InetAddress destIA,int destPort){ byte[] buf=new byte[s.length()+1]; s.getBytes(0,s.length(),buf,0); return new DatagramPacket(buf,buf.length,destIA,destPort); }
public static String toString(DatagramPacket p){ return new String(p.getData(),0,p.getLength()); } }
|
|