本帖最后由 、__WSD吴少东 于 2013-4-27 12:55 编辑
事情是这样子的,麻烦各位大神,复制下代码在自己的机子上运行下,然后通过结束标记来结束,看下是否能够结束,
在我这破机子上结束不了,我不知道是怎么回事, 麻烦各位大神了就!- /*
- 编写一个聊天小程序,
- */
- import java.io.*;
- import java.net.*;
- /*
- 需要用到多线程技术,
- */
- class Send implements Runnable
- {
- private DatagramSocket ds;
- public Send(DatagramSocket ds)
- {
- this.ds = ds;
- }
- public void run()
- {
- try
- {
- BufferedReader bufr =
- new BufferedReader(new InputStreamReader(System.in));
- String line=null;
- while((line=bufr.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);
- }
-
- }
- catch (Exception e)
- {
- throw new RuntimeException("发送端建立失败");
- }
- }
- }
- class Receive implements Runnable
- {
- private DatagramSocket ds;
- public Receive(DatagramSocket ds)
- {
- this.ds = ds;
- }
- public void run()
- {
- try
- {
- while(true)
- {
- byte[] buf = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buf,buf.length);
- ds.receive(dp);
- String ip = dp.getAddress().getHostAddress();
- String data = new String (dp.getData(),0,dp.getLength());
- System.out.println(ip+"::"+data);
- }
- }
- catch (Exception e)
- {
- throw new RuntimeException("接收端创建失败");
- }
- }
- }
- class ChartDemo
- {
- public static void main(String[] args) throws Exception
- {
- DatagramSocket sendSocket = new DatagramSocket();
- DatagramSocket receiveSocket = new DatagramSocket(10003);
- new Thread(new Send(sendSocket)).start();
- new Thread(new Receive(receiveSocket)).start();
- }
- }
复制代码 |