首页 > 其他 > 详细

群聊(udp)

时间:2017-02-20 22:22:56      阅读:174      评论:0      收藏:0      [点我收藏+]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

//群聊发送端
public class ChatSender extends Thread {
    
    @Override
    public void run() {
        try {
            //建立udp的服务
            DatagramSocket socket = new DatagramSocket();
            //准备数据,把数据封装到数据包中发送
            BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            DatagramPacket packet  = null;
            while((line = keyReader.readLine())!=null){
                //把数据封装 到数据数据包中,然后发送数据。
                packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("192.168.15.255"), 9090);
                //把数据发送出去
                socket.send(packet);
            }
            //关闭 资源
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//群聊接收端
public class ChatReceive extends Thread {
    
    @Override
    public void run() {
        try {
            //建立udp的服务,要监听一个端口
            DatagramSocket socket = new DatagramSocket(9090);
            //准备空的数据包存储数据
            byte[] buf = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            boolean flag = true;
            while(flag){
                socket.receive(packet);
                // packet.getAddress() 获取对方数据 包的IP地址对象。
                System.out.println(packet.getAddress().getHostAddress()+"说:"+new String(buf,0,packet.getLength()));
            }
            //关闭资源
            socket.close();
        
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    
    }

}
public class ChatMain {
    
    public static void main(String[] args) {
        ChatReceive chatReceive = new ChatReceive();
        chatReceive.start();
        
        ChatSender chatSender = new ChatSender();
        chatSender.start();
        
        
    }

}

 

群聊(udp)

原文:http://www.cnblogs.com/xufengyuan/p/6421716.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!