Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Last active August 11, 2019 11:36
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomasdarimont/c5fcb95a7fbbc562cee5b0b3fccf74e8 to your computer and use it in GitHub Desktop.
Save thomasdarimont/c5fcb95a7fbbc562cee5b0b3fccf74e8 to your computer and use it in GitHub Desktop.
Example to demonstrate sharing of ServerSocket ports with Java 9

Run the SharedServerSocketPortExample two times:

Then try to connect via telnet localhost 6666 from two shells.

package demo.net;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.StandardSocketOptions;
import java.util.UUID;
public class SharedServerSocketPortExample {
public static void main(String[] args) throws IOException {
try (ServerSocket ss = new ServerSocket()) {
ss.setOption(StandardSocketOptions.SO_REUSEPORT, true);
ss.bind(new InetSocketAddress(6666));
UUID instanceId = UUID.randomUUID();
System.out.printf("Instance: %s listening on: %s%n", instanceId, ss);
byte[] prefix = ("From " + instanceId + ": ").getBytes();
Socket client = ss.accept();
client.getInputStream().transferTo(new FilterOutputStream(client.getOutputStream()) {
@Override
public void write(byte[] b, int off, int len) throws IOException {
super.write(prefix, 0, prefix.length);
super.write(b, off, len);
}
});
}
}
}
@bigbangtomato
Copy link

good job. help me a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment