1 17 package org.apache.log.output.net; 18 19 import java.io.IOException ; 20 import java.net.DatagramPacket ; 21 import java.net.DatagramSocket ; 22 import java.net.InetAddress ; 23 import org.apache.log.format.Formatter; 24 import org.apache.log.output.AbstractOutputTarget; 25 26 33 public class DatagramOutputTarget 34 extends AbstractOutputTarget 35 { 36 private static final String DEFAULT_ENCODING = "US-ASCII"; 38 39 private DatagramSocket m_socket; 41 42 private String m_encoding; 44 45 54 public DatagramOutputTarget( final InetAddress address, 55 final int port, 56 final Formatter formatter, 57 final String encoding ) 58 throws IOException 59 { 60 super( formatter ); 61 m_socket = new DatagramSocket (); 62 m_socket.connect( address, port ); 63 m_encoding = encoding; 64 open(); 65 } 66 67 75 public DatagramOutputTarget( final InetAddress address, 76 final int port, 77 final Formatter formatter ) 78 throws IOException 79 { 80 this( address, port, formatter, DEFAULT_ENCODING ); 81 } 82 83 90 public DatagramOutputTarget( final InetAddress address, final int port ) 91 throws IOException 92 { 93 this( address, port, null ); 94 } 95 96 101 protected void write( final String stringData ) 102 { 103 104 try 105 { 106 final byte[] data = stringData.getBytes( m_encoding ); 107 final DatagramPacket packet = new DatagramPacket ( data, data.length ); 108 m_socket.send( packet ); 109 } 110 catch( final IOException ioe ) 111 { 112 getErrorHandler().error( "Error sending datagram.", ioe, null ); 113 } 114 } 115 116 120 public synchronized void close() 121 { 122 super.close(); 123 m_socket = null; 124 } 125 } 126 | Popular Tags |