zoukankan      html  css  js  c++  java
  • java 网络编程(三)简单的即时通讯(UDP传输)

    发送端:

    package cn.sasa.netDemo2;
    
    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    import java.util.Scanner;
    
    public class SendDemo {
    
        public static void main(String[] args) throws IOException {
            /**
             * 
             */
            Scanner scanner = new Scanner(System.in);
            DatagramSocket socket = new DatagramSocket();//发送使用空参构造函数
            InetAddress host = InetAddress.getByName("127.0.0.1");
            
            while(true) {
                String input = scanner.nextLine();
                byte[] buff = input.getBytes();
                DatagramPacket packet = new DatagramPacket(buff, buff.length, host, 8046);
                socket.send(packet);//调用send
            }
        }
    }

    接收端:

    package cn.sasa.netDemo2;
    
    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    
    public class ReceiveDemo {
    
        public static void main(String[] args) throws IOException {
            DatagramSocket socket = new DatagramSocket(8046);
            byte[] buff = new byte[1024];
            
            while(true) {
                DatagramPacket packet = new DatagramPacket(buff, buff.length);
                socket.receive(packet);
                int length = packet.getLength();//接收的字节长度
                System.out.println(new String(buff,0,length)+"==="+packet.getAddress().getHostAddress());
            }
        }
    }
  • 相关阅读:
    第一个Polymer应用
    Android-注解处理器
    怎样启动JDBC Debug模式,打印JDBC诊断日志
    OA项目之权限设计②
    Redis安装教程
    Skyscrapers Aren’t Scalable
    codeforces 183B
    iOS-NSMutableParagraphStyle段落风格
    【Java集合源代码剖析】Java集合框架
    经常使用的Hql语句
  • 原文地址:https://www.cnblogs.com/SasaL/p/10304253.html
Copyright © 2011-2022 走看看