import java.net.*; import java.util.*; import java.io.*; import java.text.*; import java.sql.*; public class Server { static final int PORT = 26482; DatagramSocket ds = null; boolean keepRunning = true; Connection con = null; Statement st = null; public static void main(String[] args) { Server server = new Server(); server.startServing(); } public Server() { try { ds = new DatagramSocket(PORT); try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); con = DriverManager.getConnection("jdbc:mysql:///houselog", "username", "password"); System.out.println("Success opening database"); } catch (ClassNotFoundException e) { System.out.println("cant find class"); } catch (SQLException ee) { System.out.println("SQL exception " + ee.getMessage()); } catch (InstantiationException ie) { System.out.println("instantiation exception "); } catch (IllegalAccessException iae) { System.out.println("illegal access exception "); } } catch (SocketException exp) {} } public void startServing() { InetAddress add; long datetimestamp; byte b; byte[] dataBuffer = new byte[4]; byte[] dataBuffer1 = new byte[9]; b = 0; while(keepRunning) { try { DatagramPacket dprec = new DatagramPacket(dataBuffer, dataBuffer.length); ds.receive(dprec); add = dprec.getAddress(); String s = new String(dprec.getData()); System.out.println("Receive UDP " + s); System.out.println("Writing to database..."); datetimestamp = System.currentTimeMillis(); PreparedStatement sql = con.prepareStatement( "INSERT INTO table1 VALUES(?, ?)" ); sql.clearParameters(); sql.setLong( 1, datetimestamp ); sql.setBytes( 2, dataBuffer); sql.executeUpdate(); System.out.println("Sending ack"); dataBuffer1[0] = 0x03; // number of bytes to send dataBuffer1[1] = (byte) 0xFC; // compliment of number of bytes to send dataBuffer1[2] = 0x03; // low byte of address dataBuffer1[3] = 0x00; // high byte of address dataBuffer1[4] = 0x41; dataBuffer1[5] = 0x41; dataBuffer1[6] = 0x41; dataBuffer1[7] = 0x00; // udp must end with two zero bytes dataBuffer1[8] = 0x00; DatagramPacket dpsend = new DatagramPacket(dataBuffer1, dataBuffer1.length, add, PORT); ds.send(dpsend); } catch (IOException expe) {} catch (SQLException sqle) { System.out.println("error " + sqle.getMessage()); } } } }