Udp实现简单的聊天程序

在《UDP通讯协议》这篇文章中,简单的说明了Udp协议特征及如何Udp协议传输数据

这里将用Udp协议技术,编写一个简单的聊天程序:

//发送端:

package com.shindo.java.udp;
import java.io.*;
import java.net.*;
/**
 * 使用多线程技术封装发送端
 */
public class UdpSendByThread implements Runnable {

    private DatagramSocket ds;
    public UdpSendByThread(DatagramSocket ds){
        this.ds = ds;
    }
    public void run(){
            //读取键盘录入
            BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
            //按行读取数据,并发送出去
            String line = null;
            try {
                while((line = bufr.readLine()) != null){
                    if("byebye".equals(line)) break;
                    
                    byte[] buf = line.getBytes();
                    
                    DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),11011);
                    
                    ds.send(dp);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        
    }
}

 

//接收端:

package com.shindo.java.udp;
import java.io.*;
import java.net.*;
/**
 * 使用多线程技术封装接收端
 */
public class UdpReceiveByThread implements Runnable{
    
    private DatagramSocket ds;
    public UdpReceiveByThread(DatagramSocket ds){
        this.ds = ds;
    }
    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();
                System.out.println(ip + "..........isconnected");
                
                String data = new String(dp.getData(),0,dp.getLength());
                System.out.println(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

启动类:

package com.shindo.java.udp;
import java.net.*;
/**
 * 实现使用Udp协议通讯的简单聊天程序
 */
public class ChatDemo {
    public static void main(String[] args) throws Exception{
        DatagramSocket ds = new DatagramSocket();
        DatagramSocket dsPort = new DatagramSocket(11011);
        
        new Thread(new UdpSendByThread(ds)).start();
        new Thread(new UdpReceiveByThread(dsPort)).start();
        
    }
}

 

posted @ 2016-03-20 09:02  shindoyang  阅读(2121)  评论(0编辑  收藏  举报