Java實現UDP傳輸方式同步發送並接收消息

在與別的服務器進行通信的過程中,我們一般是通過UDP或TCP連接,往服務器的指定IP地址和端口發送消息,然後監聽與服務器連接時指定的接收信息的端口,但是這樣就是異步通信了,我們還需要使用WebSocket往前端頁面推送消息,這時就產生了如下的需求:

同步發送和接受消息,這樣一個Ajax請求就可以實現發送和接收信息,且不需要指定接收返回信息的端口,服務器原路返回即可。

而TCP連接一定是異步的,所以只能使用UDP連接,且使用UDP連接還可以使項目在需要用的時候才連接,不用一直保持連接狀態,節省資源。

代碼如下:

<!-- 字符串轉JSON對象 -->
<!-- 第一種寫法依賴 -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>
<!-- 第二種寫法依賴 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.78</version>
</dependency>
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class UdpClass {
  
    /**
     * UDP發送並接收消息
     * @param ipAddress IP地址
     * @param port 端口號
     * @param message 消息
     */
    public static String UdpClient(String ipAddress, Integer port, String message) {
        String receiveStr = "";
        try {
            DatagramSocket datagramSocket = new DatagramSocket();
            // 設置超時時間
            datagramSocket.setSoTimeout(5000);
            byte[] buf = message.getBytes();
            InetAddress address = InetAddress.getByName(ipAddress);
            // 封裝一個數據包
            DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length, address, port);
            datagramSocket.send(datagramPacket);
            // 接收返回數據
            byte[] receiveBuf = new byte[1024000];
            DatagramPacket receivePacket = new DatagramPacket(receiveBuf, receiveBuf.length);
            datagramSocket.receive(receivePacket);
            receiveStr = new String(receivePacket.getData(), 0, receivePacket.getLength());
            datagramSocket.close();
        } catch (Exception e) {
            throw new ParameterException(1001, "消息發送失敗");
        }
        return receiveStr;
    }
    
    /**
     * 解析接收信息
     * @param receiveStr 接收信息
     */
    public static void sendMessage(String receiveStr) {
        // 使receiveStr變成JSON對象格式,例如:{"RES": 0}
        receiveStr = "{" + receiveStr + "}";
        
        // 第一種寫法
        Gson gson = new Gson();
        JSONObject jsonObject = new JSONObject();
        jsonObject = gson.fromJson(receiveStr, jsonObject.getClass());
        String res = jsonObject.get("RES");

        // 第二種寫法
        // JSONObject jsonObject = JSON.parseObject(receiveStr);
        // String res = jsonObject.getString("RES");
        System.out.println(res);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章