Java教程

自学java——网络编程UDP实现通信

本文主要是介绍自学java——网络编程UDP实现通信,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

实体类UdpSenderDemo01

客户端代码:

package com.wang.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;


public class UdpSenderDemo01 {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8888);

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            String data = reader.readLine();
            byte[] datas = data.getBytes();

            DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));

            socket.send(packet);
            if (data.equals("bye")){
                break;
            }
        }

        socket.close();

    }

}

———————————————————————————————————————————

实体类UdpReceiveDemo01

服务端代码:

package com.wang.chat;

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


public class UdpReceiveDemo01 {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(6666);

        while (true){
            //接受包裹
            byte[] container = new byte[1024];

            DatagramPacket packet = new DatagramPacket(container,0,container.length);

            socket.receive(packet);//阻塞式接受包裹

            byte[] data = packet.getData();

//            String receiveData = new String(packet.getData(),0,packet.getLength());
            String receiveData = new String(data,0, packet.getLength());
            System.out.println(receiveData);
            //断开连接 bye
            if (receiveData.equals("bye")) {
                break;
            }

        }
        socket.close();

    }
}
这篇关于自学java——网络编程UDP实现通信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!