黑马程序员技术交流社区

标题: 分享一个聊天程序代码 [打印本页]

作者: 梦里听传说    时间: 2014-9-11 19:34
标题: 分享一个聊天程序代码
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("接收失败");
                }
        }
}



作者: iefegend    时间: 2014-9-11 20:34
谢谢分享




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2