OnJava8-Examples/network/ChatterServer.java

42 lines
1.3 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// network/ChatterServer.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// A server that echoes datagrams
package network;
2015-06-15 17:47:35 -07:00
import java.net.*;
import java.io.*;
public class ChatterServer implements Runnable {
2015-06-15 17:47:35 -07:00
static final int INPORT = 1711;
private byte[] buf = new byte[1000];
private DatagramPacket dp =
new DatagramPacket(buf, buf.length);
public void run() {
2016-09-03 12:17:25 -06:00
// Can listen & send on the same socket:
try (
DatagramSocket socket = new DatagramSocket(INPORT)
) {
2015-06-15 17:47:35 -07:00
System.out.println("Server started");
while(true) {
// Block until a datagram appears:
socket.receive(dp);
String rcvd = Dgram.toString(dp) +
", from address: " + dp.getAddress() +
", port: " + dp.getPort();
System.out.println(rcvd);
String echoString =
"Echoed: " + rcvd;
// Extract the address and port from the
// received datagram to find out where to
2016-08-31 12:30:03 -06:00
// send it back to:
2015-06-15 17:47:35 -07:00
DatagramPacket echo =
Dgram.toDatagram(echoString,
dp.getAddress(), dp.getPort());
socket.send(echo);
}
} catch(IOException e) { throw new RuntimeException(e); }
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}