继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

编程实现基于udp的多用户登录

落子鸢
关注TA
已关注
手记 9
粉丝 2
获赞 64
public class ServerThread extends Thread {

    DatagramSocket socket = null;

    public ServerThread(DatagramSocket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            byte[] data = new byte[1024];// 创建字节数组,指定接收的数据包的大小
            DatagramPacket packet = new DatagramPacket(data, data.length);
            // 3接收客户端发送的数据

            socket.receive(packet);
            // 此方法在接收到数据包之前会一直阻塞
            // 4.读取数据
            String info = new String(data, 0, packet.getLength());
            System.out.println("我是服务器,客户端说:" + info);
            /*
             * 向服务器端相应
             */
            // 1.定义客户端的地址,端口号,数据
            InetAddress address = packet.getAddress();
            int port = packet.getPort();
            byte[] data2 = "欢迎你".getBytes();
            // 2创建数据报包含相应信息
            DatagramPacket packet2 = new DatagramPacket(data2, data2.length, address, port);
            // 3.响应客户端
            socket.send(packet2);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

public class UDPserver {

    public static void main(String[] args) throws IOException, InterruptedException {
        //1.创建服务器端dategramsocket,指定端口
        DatagramSocket socket = new DatagramSocket(8800);
        //2.创建数据报,用于接收客户端发送的数据
        System.out.println("*********服务器已启动等待客户端发送数据*********");
        int count = 0;

        while(true){
            ServerThread thread = new ServerThread(socket);
            thread.sleep(1000);
            thread.start();
            count++;
            System.out.println("客户端第"+count+"次连接服务器端");
        }

    }
}

public class UDPclient {

    public static void main(String[] args) throws IOException {
        //向服务器端发送数据
        //1.定义服务器的地址,端口号,数据
        InetAddress address = InetAddress.getByName("localhost");
        int port = 8800;
        byte [] data = "用户名 :admir ;密码:123;".getBytes();
        DatagramPacket packet = new DatagramPacket(data, data.length, address, port);

        DatagramSocket socket  = new DatagramSocket();
        socket.send(packet);
        //接收响应信息
        //1.创建数据报,用于接收服务器端响应信息
        byte [] data2 = new byte[1024];
        DatagramPacket packet2 = new DatagramPacket(data2, data.length);
        socket.receive(packet2);
        //3.读取数据
        String reply = new String(data2,0,packet2.getLength());
        System.out.println("我是客户端,服务器端说:"+reply);

    }
}
打开App,阅读手记
3人推荐
发表评论
随时随地看视频慕课网APP