java實現UDP通訊

mpsky發表於2021-09-09

1.概述

用DatagramSocket與DatagramPacket實現UDP通訊.UDP比TCP相對來說簡單一點,不需要等待連線,且處理資料不需要用輸出輸出流,只需要DatagramPacket.嚴格來說,UDP沒有服務端和客戶端之分,只有傳送端與接收端之分.

2.傳送端

傳送端首先建立DatagramSocket與DatagramPacket,設定好DatagramPacket的埠與ip,再透過DatagramSocket傳送.

(1)建立DatagramSocket與DatagramPacket

DatagramSocket socket = new DatagramSocket(55555);

這裡的55555埠是指資料透過這個埠傳送.

(2)建立DatagramPacket

InetAddress ip = InetAddress.getByName("127.0.0.1");
int port = 12345;
String message = "message";
DatagramPacket packet = new DatagramPacket(message.getBytes(),message.getBytes().length,ip,port);

構造方法DatagramPacket()的四個引數分別為

  • 傳送的位元組陣列
  • 位元組陣列長度
  • ip

這裡埠不能與上面的一致,不然的話會提示埠被佔用.

(3)傳送

socket.send(packet);

3.接收端

接收端只需指定埠進行接收,這裡的埠在DatagramSocket中的構造方法中指定,與傳送端的傳送的packet中設定的埠一致.

(1)建立DatagramSocket

DatagramSocket socket = new DatagramSocket(12345);

(2)建立DatagramPacket

這裡建立的DatagramPacket只需要指定儲存資料的位元組陣列與該位元組陣列的長度.

byte [] message = new byte[2048];
DatagramPacket packet = new DatagramPacket(message, message.length);

(3)接收

socket.receive(packet);

這個方法會阻塞,直到接收到packet.

(4)獲取資料

接收到packet後可以使用getData()獲取資料,返回位元組陣列,可以傳遞給String的構造方法建立String.

String str = new String(packet.getData());

4.完整程式碼

這裡人為地設定了客戶端與服務端,可以互相傳送資料,服務端輸入後傳送到服務端,服務端返回固定資料,
"客戶端"與"服務端"輪流扮演了傳送端與接收端的角色.配合了swing使用.

(1)Server.java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.*;

public class Server
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Server");
        JTextArea text = new JTextArea();

        frame.add(text);
        frame.setSize(600, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        try
        {
            byte [] message = new byte[2048];
            DatagramSocket socket = new DatagramSocket(12345);
            DatagramPacket packet = new DatagramPacket(message, message.length);
            socket.receive(packet);

            InetAddress ip = packet.getAddress();
            int port = packet.getPort();
            text.setText("ip : "+ip.toString()+"n");
            text.append("port : "+port+"n");
            text.append("message : "+new String(packet.getData()));

            String messageFromServer = "Message from server";
            packet = new DatagramPacket(messageFromServer.getBytes(),messageFromServer.getBytes().length,ip,port);
            socket.send(packet);
            socket.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

(2)Client.java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;

import javax.swing.*;
import java.awt.GridLayout;
public class Client
{
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JTextArea text = new JTextArea();
        JButton send = new JButton("send");
        GridLayout layout = new GridLayout(2,1,1,1);

        frame.setLayout(layout);
        frame.setTitle("Client");
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        frame.setSize(600, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(text);
        frame.add(send);
        send.addActionListener( v->
        {
            try
            {
                InetAddress ip = InetAddress.getByName("127.0.0.1");
                int port = 12345;
                DatagramSocket socket = new DatagramSocket(55555);
                String message = text.getText();
                DatagramPacket packet = new DatagramPacket(message.getBytes(),message.getBytes().length,ip,port);
                socket.send(packet);

                byte [] messageFromServer = new byte[2048];
                packet = new DatagramPacket(messageFromServer, messageFromServer.length);
                socket.receive(packet);
                text.setText(new String(packet.getData()));
                socket.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        });
    }
}

5.測試

圖片描述

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/1806/viewspace-2824418/,如需轉載,請註明出處,否則將追究法律責任。

相關文章