A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 梦里听传说 中级黑马   /  2014-9-11 19:34  /  679 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

import java.net.*;
import java.io.*;
class khd
{
        public static void main(String[] args)
        {        try
                {
                        DatagramSocket khd=new DatagramSocket(8888);
                        BufferedReader buf=null;
                        try
                        {
                                buf=new BufferedReader(new InputStreamReader(System.in));
                                String ls=null;
                                while ((ls=buf.readLine())!=null)
                                {
                                        if (ls.equals("886"))
                                        {
                                                break;
                                        }
                                        byte lin[]=ls.getBytes();
                                        DatagramPacket bao=new DatagramPacket(lin,lin.length,InetAddress.getByName("127.0.0.1"),12345);
                                        khd.send(bao);
                                }
                        }
                        catch (IOException e)
                        {
                                throw new RuntimeException("发送失败!");
                        }
                        finally
                        {
                                try
                                {
                                        buf.close();
                                }
                                catch (IOException c)
                                {
                                        throw new RuntimeException("关闭失败!");
                                }
                        }
                }
                catch (IOException e)
                {
                        throw new RuntimeException("端口被占用!");
                }
        }
               
}
class fwq
{
        public static void main(String[] args)
        {
                byte ls[]=new byte[1024];
                try
                {
                        DatagramSocket fwq=new DatagramSocket(12345);
                        while(true)
                        {
                                DatagramPacket bao=new DatagramPacket(ls,0,ls.length);
                                fwq.receive(bao);
                                String ip=bao.getAddress().getHostAddress();
                                int dk=bao.getPort();
                                String nr=new String(bao.getData(),0,bao.getLength());
                                System.out.println(ip+":"+dk+"说:"+nr);
                        }
                }
                catch (IOException e)
                {
                        throw new RuntimeException("接收失败");
                }
        }
}


1 个回复

正序浏览
谢谢分享
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马