Sunday, May 29, 2016

Java Datagram/UDP Server and Client, run on raspberry Pi


A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed. It's simple exampls of Datagram/UDP Client and Server, modified from Java Tutorial - Writing a Datagram Client and Server.

It's assumed both server and client run on the same Raspberry Pi, so the IP is fixed "127.0.0.1", local loopback. And the port is arbitrarily chosen 4445.


In the Server side, JavaUdpServer.java, creates a DatagramSocket on port 4445. Wait for client connect, and reply with current date/time.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;

/*
reference:
https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
*/
public class JavaUdpServer {
    
    static UdpServerThread udpServerThread;

    public static void main(String[] args) throws IOException {
        System.out.println("Server start");
        System.out.println("Runtime Java: " 
                + System.getProperty("java.runtime.version"));
        
        
        new UdpServerThread().start();
    }

    private static class UdpServerThread extends Thread{
        
        final int serverport = 4445;
        
        protected DatagramSocket socket = null;
        
        public UdpServerThread() throws IOException {
            this("UdpServerThread");
        }
        
        public UdpServerThread(String name) throws IOException {
            super(name);
            socket = new DatagramSocket(serverport);
            System.out.println("JavaUdpServer run on: " + serverport);
        }

        @Override
        public void run() {
            
            while(true){
                
                try {
                    byte[] buf = new byte[256];
                    
                    // receive request
                    DatagramPacket packet = new DatagramPacket(buf, buf.length);
                    socket.receive(packet);
                    
                    String dString = new Date().toString();
                    buf = dString.getBytes();
                    
                    // send the response to the client at "address" and "port"
                    InetAddress address = packet.getAddress();
                    int port = packet.getPort();
                    System.out.println("Request from: " + address + ":" + port);
                    packet = new DatagramPacket(buf, buf.length, address, port);
                    socket.send(packet);
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
                
            }
            
        }
        
    }
    
}


In the client side, JavaUdpClient.java, sends a request to the Server, and waits for the response.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/*
reference:
https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
*/
public class JavaUdpClient {

    public static void main(String[] args) 
            throws UnknownHostException, SocketException, IOException {
        
        //Hardcode ip:port
        String ipLocalLoopback = "127.0.0.1";
        int serverport = 4445;
        
        
        System.out.println("Runtime Java: " 
                + System.getProperty("java.runtime.version"));
        System.out.println("JavaUdpClient running, connect to: " 
                + ipLocalLoopback + ":" + serverport);
        
        // get a datagram socket
        DatagramSocket socket = new DatagramSocket();
        
        // send request
        byte[] buf = new byte[256];
        InetAddress address = InetAddress.getByName(ipLocalLoopback);
        DatagramPacket packet = 
                new DatagramPacket(buf, buf.length, address, serverport);
        socket.send(packet);
        
        // get response
        packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet);
        
        String received = new String(packet.getData(), 0, packet.getLength());
        System.out.println(received);
        
        socket.close();
    }
    
}


Related:
- Android version Datagram/UDP Client
Android version Datagram/UDP Server

No comments: