Created
January 31, 2014 19:44
-
-
Save topnotcher/8741520 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package syslog; | |
import java.net.DatagramSocket; | |
import java.net.DatagramPacket; | |
import org.apache.commons.logging.Log; | |
import org.apache.commons.logging.LogFactory; | |
/** | |
* Listening UDP syslog socket. | |
* | |
* @author Greg Bowser | |
*/ | |
public class SyslogListenerUdp extends AbstractSyslogListener { | |
private static final Log log = LogFactory.getLog(SyslogListenerUdp.class); | |
protected DatagramSocket socket; | |
protected int port; | |
private Listener listener; | |
private final int BUF_SIZE = 1024; | |
private byte[] buf = new byte[BUF_SIZE]; | |
protected volatile boolean running = false; | |
public SyslogListenerUdp(int port) { | |
setPort(port); | |
} | |
public void setPort(int port) { | |
if (port < 1 || port > 65535) | |
throw new IllegalArgumentException("1 <= port <= 65535"); | |
this.port = port; | |
} | |
public void start() { | |
running = true; | |
initListener(); | |
} | |
public void stop() { | |
running = false; | |
} | |
private void receivePacket() { | |
try { | |
DatagramPacket packet = new DatagramPacket(buf, BUF_SIZE); | |
socket.receive(packet); | |
byte[] received = new byte[packet.getLength()]; | |
//copy received packet from buf to received | |
System.arraycopy(buf, 0, received, 0, packet.getLength()); | |
queuePacket(new SyslogPacket(received,packet.getAddress().getHostAddress())); | |
} catch (java.io.IOException e) { | |
log.error("Error receiving packet: ", e); | |
return; | |
} | |
} | |
protected void initListener() { | |
if ( listener == null ) { | |
listener = new Listener(); | |
(new Thread(listener, "UDP Syslog Listener port" + port)).start(); | |
} | |
} | |
private class Listener implements Runnable { | |
public void run() { | |
init(); | |
while (running) | |
//blocks. | |
receivePacket(); | |
stop(); | |
} | |
private void init() { | |
if ( socket != null && socket.isBound() ) | |
socket.close(); | |
try { | |
log.info("creating listening socket on port" + port); | |
socket = new DatagramSocket(port); | |
} catch (java.net.SocketException e) { | |
log.fatal("Erorr creating socket: ", e); | |
running = false; | |
} | |
} | |
private void stop() { | |
try { | |
socket.close(); | |
} catch (Exception e) { | |
//can't do much if it can't close... | |
} | |
socket = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment