首先是一个工具类:
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()) ; } }
然后是服务器端
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class ChartterServer { static final int INPORT =1711; private byte [] buf = new byte[1000]; private DatagramPacket dp = new DatagramPacket(buf, buf.length) ; private DatagramSocket socket ; public ChartterServer (){ try { socket = new DatagramSocket(INPORT) ; System.out.println("server start") ; while (true) { socket.receive(dp) ; String rcvd = Dgram.toString(dp)+"from:"+ dp.getAddress()+"port:"+ dp.getPort() ; System.out.println(rcvd) ; String echoString = "Echo:"+ rcvd ; DatagramPacket echo = Dgram.toDatagram(echoString, dp.getAddress(), dp.getPort()) ; socket.send(echo) ; } } catch (SocketException e) { System.err.println("can not open socked") ; System.exit(1) ; }catch (IOException e) { System.err.println("communication erro") ; e.printStackTrace() ; } } public static void main (String [] args ){ new ChartterServer() ; } }
客户端
import java.io.BufferedReader; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; public class ChatterClient extends Thread { static final int INPORT =1711; private DatagramSocket s ; private InetAddress hostAddress ; private byte [] buf = new byte[1000] ; private DatagramPacket dp = new DatagramPacket(buf, buf.length) ; private int id ; public ChatterClient (int id ){ this.id = id ; try { s = new DatagramSocket() ; hostAddress = InetAddress.getByName(null) ; } catch (SocketException e) { System.err.println("canot open socked") ; System.exit(1) ; } catch (UnknownHostException e) { System.out.println("can not find host") ; e.printStackTrace(); } System.out.println("chatterclient start") ; } public void run (){ try { for (int i =0; i<25; i++){ String outMsg = "client id:"+id+"msg:"+ i ; s.send(Dgram.toDatagram(outMsg, hostAddress, INPORT)) ; s.receive(dp) ; String rcvd = "client id :"+ 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<10; i++){ new ChatterClient(i).start() ; } } }
时间: 2024-10-28 10:26:19