本帖最后由 莫道荣 于 2013-3-21 13:38 编辑
- import java.net.*;
- import java.io.*;
- class Send implements Runnable
- {
- private DatagramSocket ds;
- public Send(DatagramSocket ds)
- {
- this.ds=ds;
- }
- public void run()
- {
- try
- {
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- String line;
- while ((line=br.readLine())!=null)
- {
- if ("886".equals(line))
- break;
- byte[] buf=line.getBytes();
- DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10003);
- ds.send(dp);
- }
- ds.close();
- }
- catch (Exception e)
- {
- throw new RuntimeException("发送失败");
- }
-
- }
- }
- class Rece implements Runnable
- {
- private DatagramSocket ds;
- public Rece(DatagramSocket ds)
- {
- this.ds=ds;
- }
- public void run()
- {
- try
- {
- byte [] buf=new byte[1024];
- DatagramPacket dp=new DatagramPacket(buf,buf.length);
- while (true)
- {
- ds.receive(dp);
- String res=new String(buf,0,dp.getLength());
- System.out.println(res);
- }
- }
- catch (Exception e)
- {
- throw new RuntimeException("接收失败");
- }
- }
- }
- class UdpClint2
- {
- public static void main(String[] args) throws Exception
- {
- new Thread(new Send(new DatagramSocket())).start();
- new Thread(new Send(new DatagramSocket(10001))).start();
- }
- }
- import java.net.*;
- import java.io.*;
- class Send implements Runnable
- {
- private DatagramSocket ds;
- public Send(DatagramSocket ds)
- {
- this.ds=ds;
- }
- public void run()
- {
- try
- {
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- String line;
- while ((line=br.readLine())!=null)
- {
- if ("exit".equals(line))
- break;
- byte[] buf=line.getBytes();
- DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10001);
- ds.send(dp);
- }
- ds.close();
- }
- catch (Exception e)
- {
- throw new RuntimeException("发送失败");
- }
-
- }
- }
- class Rece implements Runnable
- {
- private DatagramSocket ds;
- public Rece(DatagramSocket ds)
- {
- this.ds=ds;
- }
- public void run()
- {
- try
- {
- byte [] buf=new byte[1024];
- DatagramPacket dp=new DatagramPacket(buf,buf.length);
- while (true)
- {
- String ip=dp.getAddress().getHostAddress();
- ds.receive(dp);
- System.out.println(ip+"::"+new String(buf,0,dp.getLength()));
- }
- }
- catch (Exception e)
- {
- throw new RuntimeException("接收失败");
- }
- }
- }
- class UdpClint
- {
- public static void main(String[] args) throws Exception
- {
- new Thread(new Send(new DatagramSocket())).start();
- new Thread(new Send(new DatagramSocket(10003))).start();
- }
- }
复制代码
为什么两个控制台不能互相通信呢????
|