Sending TCP and UDP Packets in Java


I’ve found UDP to be a great way to send logs to a logging server fast without slowing up an application as long as you don’t care if you lose a packet or two every now and then. TCP is great for a more stable way to send the logs.

    public static void sendTCPPacketToSelf() {
        try {
            for (int i = 0; i < 1000; i++) {
                System.out.println("count: " + i);
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        try {
                            JSONObject json = new JSONObject();
                            json.put("count", 1);
                            //System.out.println("sending: " + json.toString());
                            SocketAddress address = new InetSocketAddress("localhost", 4446);
                            Socket clientSocket = new Socket();
                            clientSocket.connect(address, 20000); 
                            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
                            //BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                            outToServer.writeBytes(json.toString() + '\n');
                            clientSocket.close();
                        } catch(Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                };
                thread.start();
            }
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void sendUDPPacketToSelf() {
        try {
            DatagramSocket socket = new DatagramSocket(3336); // source socket
            for (int i = 0; i < 100000; i++) {
                int port = 4445; // destination port
                byte[] buf = new byte[2024];
                JSONObject json = new JSONObject();
                json.put("count", i);
                InetAddress address = InetAddress.getByName("localhost");
                System.out.println("json: " + json.toString());
                buf = json.toString().getBytes("UTF8");
                DatagramPacket packet = new DatagramPacket(buf, buf.length, address, port);
                socket.send(packet);
            }
            socket.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s