-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNIOSender.java
More file actions
32 lines (28 loc) · 1.07 KB
/
NIOSender.java
File metadata and controls
32 lines (28 loc) · 1.07 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
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class NIOSender {
public static void main(String[] args) {
try {
// Create a socket channel and connect to the receiver
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("192.168.1.100", 12345));
// Wait for the connection to be established
while (!socketChannel.finishConnect()) {
// Do nothing
}
// Send data to the receiver
String message = "Hello, world!";
ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
while (buffer.hasRemaining()) {
socketChannel.write(buffer);
}
// Close the socket channel
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}