用UDP实现聊天(多线程,IO)

package yuwei.com;

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

/*
 * 编写一个聊天程序
 * 有收数据的和发数据
 *因为收和发的动作不一样
 *因此需要两个类进行封装
 **/
class SendDemo implements Runnable{

    private DatagramSocket ds;
    SendDemo(DatagramSocket s) {
        this.ds = s;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            BufferedReader bfr = 
                    new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while((line = bfr.readLine()) != null) {
                if("886".equals(line)) {
                    break;
                }else {
                    byte[] buf = line.getBytes();
                    //定义一个数据包存储数据
                    DatagramPacket dp =
                            new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.153.1"),1);
                    ds.send(dp);
                }
            }
        }catch(IOException e) {
            throw new RuntimeException("失败");
        }finally {
            ds.close();
        }
    }

}
class Receive implements Runnable{

    private DatagramSocket ds;
    Receive(DatagramSocket ds){
        this.ds=ds;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(true) {
            byte[] buf = new byte[1024];
            DatagramPacket dp = 
                    new DatagramPacket(buf,buf.length);
            try {
                ds.receive(dp);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                throw new RuntimeException("失败");
            }
            String ip = dp.getAddress().getHostAddress();
            String data = new String (dp.getData(),0,dp.getLength());
            System.out.println(ip + ":: " + data);
        }
    }
}
public class ChatDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            SendDemo s = new SendDemo(new DatagramSocket());
            Receive r = new Receive(new DatagramSocket(1));
            new Thread(s).start();
            new Thread(r).start();

        }catch(IOException e) {
            e.printStackTrace();
        }

    }

}

你可能感兴趣的:(多线程,IO,网络编程)