Java Socket小案例(4)实时聊天

来源:互联网 发布:米思米3d数据库 编辑:程序博客网 时间:2024/05/16 06:55
//做成工具类public class UdpUtils implements Runnable {    DatagramSocket socket = null;    public UdpUtils(int port) {        try {            socket = new DatagramSocket(port);        } catch (SocketException e) {            e.printStackTrace();        }    }    public void listen() {        new Thread(this).start();    }    @Override    public void run() {        byte[] buf = new byte[1024];        DatagramPacket packet = new DatagramPacket(buf, buf.length);        try {            while (true) {                socket.receive(packet);                System.out.println(new String(packet.getData(), 0, packet                        .getLength()));            }        } catch (IOException e) {            e.printStackTrace();        }    }    public void send(String ip, int port) {        DatagramSocket socket = null;        BufferedReader bufr = null;        try {            socket = new DatagramSocket();            byte[] buf = new byte[1024];            DatagramPacket packet = new DatagramPacket(buf, buf.length,                    InetAddress.getByName(ip), port);            bufr = new BufferedReader(new InputStreamReader(System.in));            String line = null;            while ((line = bufr.readLine()) != null) {                if (line.equals("886")) {                    break;                }                packet.setData(line.getBytes(), 0, line.getBytes().length);                socket.send(packet);            }        } catch (Exception e) {            e.printStackTrace();        }    }}