本帖最后由 新航向 于 2014-9-8 08:47 编辑
以下代码比本上和视频里的一样,在本人机子上为什么会出错?(即输入内容后就卡住,也不打印地址和内容)请大神们帮忙看看,谢谢!- import java.io.*;
- import java.net.*;
- class Send implements Runnable
- {
- private DatagramSocket ds;
- Send(DatagramSocket ds)
- {
- this.ds = ds;
- }
- public void run()
- {
- try
- {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String line = null;
- while ((line=br.readLine())!=null)
- {
- if(!line.equals("886"))
- break;
- byte[] buff = line.getBytes();
- DatagramPacket dp = new DatagramPacket(buff,buff.length,InetAddress.getLocalHost(),54321);
- ds.send(dp);
- }
- ds.close();
- }
- catch (Exception e)
- {
- throw new RuntimeException("传输失败");
- }
- }
- }
- class Receive implements Runnable
- {
- private DatagramSocket ds;
- Receive(DatagramSocket ds)
- {
- this.ds = ds;
- }
- public void run()
- {
- try
- {
- while (true)
- {
- byte[] buff = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buff,buff.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 ChatDemo
- {
- public static void main(String[] args) throws Exception
- {
- DatagramSocket sendSocket = new DatagramSocket();
- DatagramSocket receiveSocket = new DatagramSocket(54321);
- new Thread(new Send(sendSocket)).start();
- new Thread(new Receive(receiveSocket)).start();
- }
- }
复制代码
|
-
1.png
(30.41 KB, 下载次数: 26)
|