黑马程序员技术交流社区

标题: udp通信——模拟qq对话 [打印本页]

作者: 我来也    时间: 2015-4-12 00:55
标题: udp通信——模拟qq对话
使用的是udp协议。可以直接使用
import java.net.*;
import java.io.*;
class Send implements Runnable
{
        private DatagramSocket ds;
        public Send(DatagramSocket ds)
        {
                this.ds=ds;
        }
        @Override
        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("223.247.190.204"),10004);
                                ds.send(dp);
                        }
                       
                }catch(IOException e)
                {
                        throw new RuntimeException("fail");
                }
               
        }
}




class Rece implements Runnable
{
        private DatagramSocket ds;
        public Rece(DatagramSocket ds)
        {
                this.ds=ds;
        }
        @Override
        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(IOException ex)
        {
                throw new RuntimeException("fail");
        }
               
               
        }
}




public class LiaoTian {


        public static void main(String[] args) throws IOException{
               


                DatagramSocket sendSocket=new DatagramSocket();
                DatagramSocket receSocket =new DatagramSocket(10004);
                new Thread(new Send(sendSocket)).start();
                new Thread(new Rece(receSocket)).start();
        }


}







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