-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNIOReceiver.java
More file actions
69 lines (61 loc) · 3.03 KB
/
NIOReceiver.java
File metadata and controls
69 lines (61 loc) · 3.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NIOReceiver {
public static void main(String[] args) {
try {
// Create a selector and a server socket channel
Selector selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(12345));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
// Wait for events
selector.select();
// Handle the events
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iter = selectedKeys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
if (key.isAcceptable()) {
// Accept the incoming connection
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
// Read data from the socket channel
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int numRead = socketChannel.read(buffer);
if (numRead == -1) {
// The connection has been closed
key.cancel();
socketChannel.close();
continue;
}
// Process the received data
String message = new String(buffer.array(), 0, numRead);
System.out.println("Received message: " + message);
// Send a response back to the sender
ByteBuffer responseBuffer = ByteBuffer.wrap("Thanks for your message!".getBytes());
while (responseBuffer.hasRemaining()) {
socketChannel.write(responseBuffer);
}
}
// Remove the processed key from the set
iter.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}