- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.*;
- public class duoxianchengliaotian
- {
- public static void main(String[]args) throws Exception
- {
- DatagramSocket sendSocket = new DatagramSocket();
- DatagramSocket resceSocket = new DatagramSocket(10000);
- send s = new send(sendSocket);
- resce r = new resce(resceSocket);
- Thread t1 = new Thread(s);
- Thread t2 = new Thread(r);
- t1.start();
- t2.start();
- }
- }
- class send implements Runnable {
- private DatagramSocket ds;
- public send(DatagramSocket ds)
- {
- this.ds=ds;
- }
- public void run()
- {
- String line =null;
- BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
- try {
- while((line=bfr.readLine())!=null)
- {
- byte[] buf = line.getBytes();
- DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.0.102"),10000);
- ds.send(dp);
-
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- class resce implements Runnable
- {
- private DatagramSocket ds;
- public resce(DatagramSocket ds)
- {
- this.ds=ds;
- }
- public void run()
- {
- String line =null;
-
- while(true)
- {
- byte[]buf = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buf, buf.length);
- try {
- ds.receive(dp);
- String ip = dp.getAddress().getHostAddress();
- String data = new String(dp.getData(),0,dp.getLength());
- System.out.println(ip+":::"+data);
-
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //ds.close();
- }
- }
- }
复制代码 |