Udp

Rooki3發表於2024-07-07

Udp協議

1.客戶端(與伺服器不需建立連線)

//1.建立socket
DatagramSocket datagramSocket = new DatagramSocket();
//2.建立一個包
String msg = "你好!";
InetAddress localhost = InetAddress.getByName("127.0.0.1");
int post = 9000;
//資料,資料起始,資料長度,資料傳送地址
DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,post);
//3.傳送包
datagramSocket.send(packet);
//4.關閉流
datagramSocket.close();

2.服務端(等待接受客戶資料)

//1.建立一個埠
DatagramSocket datagramSocket = new DatagramSocket(9000);
//2.接受資料包
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

datagramSocket.receive(packet);

System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0,packet.getLength()));
//3.關閉資源
datagramSocket.close();

3.Udp聊天

//Sender
DatagramSocket socket = new DatagramSocket(9999);

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

while (true){
    String data = reader.readLine();
    byte[] bytes = data.getBytes();
    DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length,new InetSocketAddress("localhost",9000));

    socket.send(packet);
    if(data.equals("Bye")){
        break;
    }
}
socket.close();
//Receiver
DatagramSocket socket = new DatagramSocket(9000);

while (true){
    byte[] container = new byte[1024];
    DatagramPacket packet = new DatagramPacket(container, 0,container.length);
    socket.receive(packet);

    String receiveData = new String(packet.getData(),0, packet.getLength());

    System.out.println(receiveData);

    if (receiveData.equals("Bye")){
        break;
    }
}

4.Udp多執行緒線上聊天

//傳送
public class TalkSender implements Runnable{
    DatagramSocket socket;
    BufferedReader reader;

    private int fromPort;
    private int toPort;
    private String toIP;

    public TalkSender(int fromPort, int toPort, String toIP) throws SocketException {
        this.fromPort = fromPort;
        this.toPort = toPort;
        this.toIP = toIP;

        socket = new DatagramSocket(fromPort);
        reader = new BufferedReader(new InputStreamReader(System.in));
    }

    @Override
    public void run() {
        try {
            while (true){
                String data = reader.readLine();
                byte[] bytes = data.getBytes();
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length,new InetSocketAddress(toIP,toPort));

                socket.send(packet);
                if(data.equals("Bye")){
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }
}
//接收
public class TalkReceive implements Runnable{
    DatagramSocket socket;

    private int port;

    public TalkReceive(int port) throws SocketException {
        this.port = port;
        socket = new DatagramSocket(port);
    }

    @Override
    public void run() {
        while (true){
            try {
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0,container.length);
                socket.receive(packet);

                String receiveData = new String(packet.getData(),0, packet.getLength());

                System.out.println(receiveData);

                if (receiveData.equals("Bye")){
                    break;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        socket.close();
    }
}
//學生
public class Student {
    public static void main(String[] args) throws SocketException {
        new Thread(new TalkSender(9000,9999, "localhost")).start();
        new Thread(new TalkReceive(8000)).start();
    }
}
//老師
public class Teacher {
    public static void main(String[] args) throws SocketException {
        new Thread(new TalkSender(9900,8000,"localhost")).start();
        new Thread(new TalkReceive(9999)).start();
    }
}

URL(統一資源定位符:定位資源的)

DNS 域名解析 www.baidu.com ==>xxx.x.x.x
$$
協議://IP地址:埠號/專案名/資源
$$
下載網路資源

//下載網易雲音樂
//1.下載地址物件
URL url = new URL("\n" +
        "https://m801.music.126.net/20240626104551/9e6149f5e794ca208ff3364e74f57c51/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/20289466004/7191/9c89/dca3/a0d98a2848ee5258b94cbc01a6f889c8.m4a");

//2.連線資源的http
 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
 
 //3.copy資源
InputStream is = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("music.m4a");

byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer)) != -1){
    fileOutputStream.write(buffer,0,len);
}
//4.關閉連線
is.close();
fileOutputStream.close();
urlConnection.disconnect();

相關文章