UDP聊天室 java

要求实现一个聊天室,能同时接收和发送信息。

下面的代码用两个线程在处理发送和接收信息。信息在网际的传递采用UDP协议。这种方法不需要建立连接,因此比较高效,但是正因补永济哪里连接,因此会有丢包的不安全性。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

//聊天室类
public class TalkingRoom 
{
    public static void main(String[] args) throws Exception
    {
        DatagramSocket sendds=new DatagramSocket();
        DatagramSocket receiveds=new DatagramSocket(10001);
        //两个线程,分别是发送和接收线程
        new Thread(new Send(sendds)).start();
        new Thread(new Recieve(receiveds)).start();
    }
}
//发送类
class Send implements Runnable
{
    DatagramSocket ds;
    public Send(DatagramSocket ds)
    {
        this.ds=ds;
    }
    
    public void run() 
    {
        //从键盘按行读入
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String line=null;
        try 
        {
            while((line=br.readLine())!=null)
            {
                byte[] buf=line.getBytes();
                DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.0.255"),10001);
                ds.send(dp);
                if (line.equals("over"))
                    break;
            }
        } catch (Exception e) {
            } 
        ds.close();
    }
}
// 接收类
class Recieve implements Runnable
{
    DatagramSocket ds;
    public Recieve(DatagramSocket ds)
    {
        this.ds=ds;
    }
    public void run()
    {
        while(true)
        {
            byte[] buf=new byte[1024];
            DatagramPacket dp=new DatagramPacket(buf,buf.length);
            
            try {
                ds.receive(dp);
            } catch (Exception e) {
            }
            
            String ip=dp.getAddress().getHostAddress();
            String text=new String(dp.getData(),0,dp.getLength());
            if(text.equals("over"))
                System.out.print("对方已下线");
            else
                System.out.println(ip+":"+text);
        }
    }
}

 

posted on 2018-06-13 22:12  yfyfyf947  阅读(253)  评论(0编辑  收藏  举报