UDP传输实例

网络编程就是用来实现互连的不同计算机上运行的程序进行数据交换。
使用UDP协议搭建聊天室:
一、首先创建一个线程池

public class ThreadPoolUtil {
    private static ExecutorService threadPool = Executors.newCachedThreadPool();
    public static void execute(Runnable command){
        if(threadPool.isShutdown()){
            threadPool = Executors.newCachedThreadPool();
            execute(command);
        }else{
            threadPool.execute(command);
        }
    }
    public static void shutdown(){
        if(!threadPool.isShutdown()){
            threadPool.shutdownNow();
        }
    }
}

二、建立一个客户端:

public class ClientRunnable implements Runnable {
    private String ip = "localhost";
    private int port = 8888;


    public ClientRunnable() {

    }

    public ClientRunnable(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    @Override
    public void run() {
        //1.创建客户端DatagramSocket对象
        try (DatagramSocket socket = new DatagramSocket();
            Scanner sc = new Scanner(System.in);){
            //2.创建数据包,在包中指定ip地址,端口号,内容
            String content = null;
            byte [] buf = null;
            while(true){
                content = sc.nextLine();
                if(content.equals("886")){
                    break;
                }
                 buf = content.getBytes();
                socket.send(new DatagramPacket(buf, buf.length, InetAddress.getByName(ip), port));
            }

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

}

三、建立一个服务端:

public class ServerRunnable implements Runnable {
    private int port = 8888;

    public ServerRunnable(){

    }
    public ServerRunnable(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        //1.创建DatagramSocket对象,并监听指定端口号
        try (DatagramSocket socket = new DatagramSocket(port);){
            //2.创建存储数据的字节数组容器
            byte [] buf = new byte [1024*64];
            DatagramPacket p = new DatagramPacket(buf, buf.length);
            //3.循环接收数据
            while(true){
                socket.receive(p);
                System.out.println("ip= " + p.getAddress().getHostAddress() + "content= " + new String(p.getData(),0,p.getLength()));
            }

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

}

四、使用线程池运行服务端和客户端

public class ChatRoom {
    public static void main(String[] args) {

        ServerRunnable serverRunnable = new ServerRunnable(8888);
        ThreadPoolUtil.execute(serverRunnable);
        ClientRunnable clientRunnable = new ClientRunnable("192.168.1.255",8888);
        ThreadPoolUtil.execute(clientRunnable);

    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值