OnJava8-Examples/network/ChatterServer.java

51 lines
1.5 KiB
Java
Raw Normal View History

2015-05-05 11:20:13 -07:00
//: network/ChatterServer.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-05-31 18:34:12 -07:00
// {ValidateByHand}
2015-05-05 11:20:13 -07:00
// A server that echoes datagrams
import java.net.*;
import java.io.*;
2015-05-31 18:34:12 -07:00
import net.mindview.util.*;
2015-05-05 11:20:13 -07:00
public class ChatterServer {
static final int INPORT = 1711;
private byte[] buf = new byte[1000];
2015-05-31 18:34:12 -07:00
private DatagramPacket dp =
2015-05-05 11:20:13 -07:00
new DatagramPacket(buf, buf.length);
// Can listen & send on the same socket:
private DatagramSocket socket;
public ChatterServer() {
try {
socket = new DatagramSocket(INPORT);
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);
2015-05-31 18:34:12 -07:00
String echoString =
2015-05-05 11:20:13 -07:00
"Echoed: " + rcvd;
// Extract the address and port from the
// received datagram to find out where to
// send it back:
2015-05-31 18:34:12 -07:00
DatagramPacket echo =
2015-05-05 11:20:13 -07:00
Dgram.toDatagram(echoString,
dp.getAddress(), dp.getPort());
socket.send(echo);
}
} catch(SocketException e) {
System.err.println("Can't open socket");
System.exit(1);
} catch(IOException e) {
2015-05-30 19:07:15 -07:00
System.out.println("Communication error");
2015-05-05 11:20:13 -07:00
e.printStackTrace();
}
}
public static void main(String[] args) {
2015-05-31 18:34:12 -07:00
new TimedAbort(5); // Terminate after 5 seconds
2015-05-05 11:20:13 -07:00
new ChatterServer();
}
} ///:~