ServerSocketChannel
In this chapter you will learn:
- New IO Hello Server
- Accepting a Connection on a ServerSocketChannel
- non-blocking accept() using ServerSocketChannel
New IO Hello Server
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
/*from j a va2s.co m*/
public class MainClass {
public final static int PORT = 2345;
public static void main(String[] args) throws Exception {
ServerSocketChannel serverChannel = ServerSocketChannel.open();
SocketAddress port = new InetSocketAddress(PORT);
serverChannel.socket().bind(port);
while (true) {
SocketChannel clientChannel = serverChannel.accept();
String response = "Hello " + clientChannel.socket().getInetAddress() + " on port "
+ clientChannel.socket().getPort() + "\r\n";
response += "This is " + serverChannel.socket() + " on port "
+ serverChannel.socket().getLocalPort() + "\r\n";
byte[] data = response.getBytes("UTF-8");
ByteBuffer buffer = ByteBuffer.wrap(data);
while (buffer.hasRemaining())
clientChannel.write(buffer);
clientChannel.close();
}
}
}
Accepting a Connection on a ServerSocketChannel
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
//ja v a 2 s. com
public class Main {
public static void main(String[] argv) throws Exception {
ServerSocketChannel ssChannel = ServerSocketChannel.open();
ssChannel.configureBlocking(false);
int port = 80;
ssChannel.socket().bind(new InetSocketAddress(port));
int localPort = ssChannel.socket().getLocalPort();
SocketChannel sChannel = ssChannel.accept();
if (sChannel == null) {
} else {
}
}
}
non-blocking accept() using ServerSocketChannel
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
/* ja va 2 s . c o m*/
public class MainClass {
public static final String GREETING = "Hello I must be going.\r\n";
public static void main(String[] argv) throws Exception {
int port = 1234; // default
ByteBuffer buffer = ByteBuffer.wrap(GREETING.getBytes());
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(port));
ssc.configureBlocking(false);
while (true) {
System.out.println("Waiting for connections");
SocketChannel sc = ssc.accept();
if (sc == null) {
Thread.sleep(2000);
} else {
System.out.println("Incoming connection from: " + sc.socket().getRemoteSocketAddress());
buffer.rewind();
sc.write(buffer);
sc.close();
}
}
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Socket