package com.haobang.syslog;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class TestSyslogServer {
    public static void main(String[] args) throws Throwable {
        // TODO Auto-generated method stub
        DatagramSocket datagramSocket = new DatagramSocket(514);
        while (true) {
            DatagramPacket packet = new DatagramPacket(new byte[1000], 1000);
            try {
                //不会造成死循环，因为receive是阻塞式方法，若发送方不发送数据，则阻塞在该处
                datagramSocket.receive(packet);
                String msg = new String(packet.getData(), 0, packet.getLength());
                //handelMessage(msg);

                System.out.println(packet.getAddress() + "/" + packet.getPort() + ":" + msg);
                packet.setData("I am server!!!".getBytes());
                datagramSocket.send(packet);
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    public static void handelMessage(String messageFragment){
        StringBuilder currentMessage = new StringBuilder();
        boolean isSplitMessage = messageFragment.endsWith("..."); // 根据拆分标志判断消息是否被拆分

        if (isSplitMessage) {
            // 拆分的消息片段，将其合并到当前消息
            currentMessage.append(messageFragment.substring(0, messageFragment.length() - 3));
        } else {
            // 完整的消息，处理并重置当前消息
            currentMessage.append(messageFragment);
            handleCompleteMessage(currentMessage.toString());
            currentMessage.setLength(0);
        }
    }
    public static void handleCompleteMessage(String completeMessage){
        System.out.println("接收到完整消息：" + completeMessage);
    }
}
