|
| 1 | +/** |
| 2 | + * Copyright (C) 2015 Roland Kuhn <http://rolandkuhn.com> |
| 3 | + */ |
| 4 | +package com.reactivedesignpatterns.chapter14; |
| 5 | + |
| 6 | +import java.io.IOException; |
| 7 | +import java.net.DatagramPacket; |
| 8 | +import java.net.DatagramSocket; |
| 9 | +import java.net.InetSocketAddress; |
| 10 | +import java.net.SocketAddress; |
| 11 | + |
| 12 | +public class RequestResponse { |
| 13 | + private static final int SERVER_PORT = 8888; |
| 14 | + |
| 15 | + static public class Server { |
| 16 | + static public void main(String[] args) throws IOException { |
| 17 | + // bind a socket for receiving packets |
| 18 | + try (final DatagramSocket socket = new DatagramSocket(SERVER_PORT)) { |
| 19 | + |
| 20 | + // receive one packet |
| 21 | + final byte[] buffer = new byte[1500]; |
| 22 | + final DatagramPacket packet1 = new DatagramPacket(buffer, buffer.length); |
| 23 | + socket.receive(packet1); |
| 24 | + |
| 25 | + final SocketAddress sender = packet1.getSocketAddress(); |
| 26 | + System.out.println("server: received " + new String(packet1.getData())); |
| 27 | + System.out.println("server: sender was " + sender); |
| 28 | + |
| 29 | + // send response back |
| 30 | + final byte[] response = "got it!".getBytes(); |
| 31 | + final DatagramPacket packet2 = new DatagramPacket(response, response.length, sender); |
| 32 | + socket.send(packet2); |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + static public class Client { |
| 38 | + static public void main(String[] args) throws IOException { |
| 39 | + // get local socket with random port |
| 40 | + try (final DatagramSocket socket = new DatagramSocket()) { |
| 41 | + |
| 42 | + // send message to server |
| 43 | + final byte[] request = "hello".getBytes(); |
| 44 | + final DatagramPacket packet1 = new DatagramPacket(request, request.length, |
| 45 | + new InetSocketAddress("localhost", SERVER_PORT)); |
| 46 | + socket.send(packet1); |
| 47 | + |
| 48 | + // receive one packet |
| 49 | + final byte[] buffer = new byte[1500]; |
| 50 | + final DatagramPacket packet2 = new DatagramPacket(buffer, buffer.length); |
| 51 | + socket.receive(packet2); |
| 52 | + |
| 53 | + final SocketAddress sender = packet2.getSocketAddress(); |
| 54 | + System.out.println("client: received " + new String(packet2.getData())); |
| 55 | + System.out.println("client: sender was " + sender); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments