Skip to content

Commit d8ea117

Browse files
authored
Bael 9177 (#18396)
* BAEL-9177 * BAEL-9177 add test server connection test case
1 parent 4331b39 commit d8ea117

File tree

5 files changed

+260
-0
lines changed

5 files changed

+260
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.baeldung.socketchannel;
2+
3+
import java.io.*;
4+
import java.net.InetSocketAddress;
5+
import java.nio.ByteBuffer;
6+
import java.nio.channels.ServerSocketChannel;
7+
import java.nio.channels.SocketChannel;
8+
9+
public class BlockingServer {
10+
private static final int PORT = 6000;
11+
12+
public static void main(String[] args) {
13+
try (ServerSocketChannel serverSocket = ServerSocketChannel.open()) {
14+
serverSocket.bind(new InetSocketAddress(PORT));
15+
System.out.println("Blocking Server listening on port " + PORT);
16+
17+
while (true) {
18+
try (SocketChannel clientSocket = serverSocket.accept()) {
19+
System.out.println("Client connected");
20+
MyObject obj = receiveObject(clientSocket);
21+
System.out.println("Received: " + obj.getName() + ", " + obj.getAge());
22+
} catch (ClassNotFoundException e) {
23+
e.printStackTrace();
24+
}
25+
}
26+
} catch (IOException e) {
27+
e.printStackTrace();
28+
}
29+
}
30+
31+
private static MyObject receiveObject(SocketChannel channel)
32+
throws IOException, ClassNotFoundException {
33+
ByteBuffer buffer = ByteBuffer.allocate(1024);
34+
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
35+
36+
int bytesRead;
37+
while ((bytesRead = channel.read(buffer)) > 0) {
38+
buffer.flip();
39+
byteStream.write(buffer.array(), 0, buffer.limit());
40+
buffer.clear();
41+
}
42+
43+
byte[] bytes = byteStream.toByteArray();
44+
try (ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
45+
return (MyObject) objIn.readObject();
46+
}
47+
}
48+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.baeldung.socketchannel;
2+
3+
import java.io.*;
4+
import java.net.InetSocketAddress;
5+
import java.nio.ByteBuffer;
6+
import java.nio.channels.SocketChannel;
7+
8+
public class Client {
9+
private static final String SERVER_ADDRESS = "localhost";
10+
private static final int SERVER_PORT = 6000;
11+
12+
public static void main(String[] args) {
13+
try (SocketChannel socketChannel = SocketChannel.open()) {
14+
socketChannel.connect(new InetSocketAddress(SERVER_ADDRESS, SERVER_PORT));
15+
System.out.println("Connected to server");
16+
17+
MyObject objectToSend = new MyObject("Alice", 25);
18+
sendObject(socketChannel, objectToSend);
19+
System.out.println("Object sent");
20+
} catch (IOException e) {
21+
e.printStackTrace();
22+
}
23+
}
24+
25+
private static void sendObject(SocketChannel channel, MyObject obj)
26+
throws IOException {
27+
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
28+
try (ObjectOutputStream objOut = new ObjectOutputStream(byteStream)) {
29+
objOut.writeObject(obj);
30+
}
31+
byte[] bytes = byteStream.toByteArray();
32+
33+
ByteBuffer buffer = ByteBuffer.wrap(bytes);
34+
while (buffer.hasRemaining()) {
35+
channel.write(buffer);
36+
}
37+
}
38+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.baeldung.socketchannel;
2+
3+
import java.io.Serializable;
4+
5+
class MyObject implements Serializable {
6+
7+
private String name;
8+
private int age;
9+
10+
public MyObject(String name, int age) {
11+
this.name = name;
12+
this.age = age;
13+
}
14+
15+
public String getName() {
16+
return name;
17+
}
18+
19+
public int getAge() {
20+
return age;
21+
}
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package com.baeldung.socketchannel;
2+
3+
import java.io.*;
4+
import java.net.InetSocketAddress;
5+
import java.nio.ByteBuffer;
6+
import java.nio.channels.*;
7+
import java.util.Iterator;
8+
import java.util.Set;
9+
10+
public class NonBlockingServer {
11+
private static final int PORT = 6000;
12+
13+
public static void main(String[] args) throws IOException {
14+
ServerSocketChannel serverChannel = ServerSocketChannel.open();
15+
serverChannel.bind(new InetSocketAddress(PORT));
16+
serverChannel.configureBlocking(false);
17+
18+
Selector selector = Selector.open();
19+
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
20+
21+
System.out.println("Non-blocking Server listening on port " + PORT);
22+
23+
while (true) {
24+
selector.select();
25+
Set<SelectionKey> keys = selector.selectedKeys();
26+
Iterator<SelectionKey> iter = keys.iterator();
27+
28+
while (iter.hasNext()) {
29+
SelectionKey key = iter.next();
30+
iter.remove();
31+
32+
if (key.isAcceptable()) {
33+
SocketChannel client = serverChannel.accept();
34+
client.configureBlocking(false);
35+
client.register(selector, SelectionKey.OP_READ);
36+
System.out.println("New client connected");
37+
}
38+
else if (key.isReadable()) {
39+
SocketChannel client = (SocketChannel) key.channel();
40+
try {
41+
MyObject obj = receiveObject(client);
42+
if (obj != null) {
43+
System.out.println("Received: " + obj.getName() + ", " + obj.getAge());
44+
}
45+
} catch (ClassNotFoundException e) {
46+
e.printStackTrace();
47+
client.close();
48+
}
49+
}
50+
}
51+
}
52+
}
53+
54+
private static MyObject receiveObject(SocketChannel channel)
55+
throws IOException, ClassNotFoundException {
56+
ByteBuffer buffer = ByteBuffer.allocate(1024);
57+
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
58+
59+
int bytesRead;
60+
while ((bytesRead = channel.read(buffer)) > 0) {
61+
buffer.flip();
62+
byteStream.write(buffer.array(), 0, buffer.limit());
63+
buffer.clear();
64+
}
65+
66+
if (bytesRead == -1) {
67+
channel.close();
68+
return null;
69+
}
70+
71+
byte[] bytes = byteStream.toByteArray();
72+
try (ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
73+
return (MyObject) objIn.readObject();
74+
}
75+
}
76+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package com.baeldung.socketchannel;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertTrue;
5+
6+
import java.io.ObjectInputStream;
7+
import java.io.ObjectOutputStream;
8+
import java.net.InetSocketAddress;
9+
import java.nio.channels.Channels;
10+
import java.nio.channels.ServerSocketChannel;
11+
import java.nio.channels.SocketChannel;
12+
import java.util.concurrent.ExecutorService;
13+
import java.util.concurrent.Executors;
14+
import java.util.concurrent.Future;
15+
import java.util.concurrent.TimeUnit;
16+
17+
import org.junit.jupiter.api.Test;
18+
19+
public class SocketChannelUnitTest {
20+
21+
@Test
22+
void givenServerStarted_whenClientConnects_thenConnectionIsSuccessful() throws Exception {
23+
try (ServerSocketChannel server = ServerSocketChannel.open()
24+
.bind(new InetSocketAddress(6000))) {
25+
int port = ((InetSocketAddress) server.getLocalAddress()).getPort();
26+
ExecutorService executor = Executors.newSingleThreadExecutor();
27+
Future<Boolean> future = executor.submit(() -> {
28+
try (SocketChannel client = server.accept()) {
29+
return client.isConnected();
30+
}
31+
});
32+
try (SocketChannel client = SocketChannel.open()) {
33+
client.configureBlocking(true);
34+
client.connect(new InetSocketAddress("localhost", 6000));
35+
while (!client.finishConnect()) {
36+
Thread.sleep(10);
37+
}
38+
}
39+
assertTrue(future.get(2, TimeUnit.SECONDS));
40+
executor.shutdown();
41+
}
42+
}
43+
44+
@Test
45+
void givenClientSendsObject_whenServerReceives_thenDataMatches() throws Exception {
46+
try (ServerSocketChannel server = ServerSocketChannel.open()
47+
.bind(new InetSocketAddress(6000))) {
48+
int port = ((InetSocketAddress) server.getLocalAddress()).getPort();
49+
ExecutorService executor = Executors.newSingleThreadExecutor();
50+
Future<MyObject> future = executor.submit(() -> {
51+
try (SocketChannel client = server.accept(); ObjectInputStream objIn = new ObjectInputStream(Channels.newInputStream(client))) {
52+
return (MyObject) objIn.readObject();
53+
}
54+
});
55+
56+
try (SocketChannel client = SocketChannel.open()) {
57+
client.configureBlocking(true);
58+
client.connect(new InetSocketAddress("localhost", 6000));
59+
60+
// Ensure connection is fully established before writing
61+
while (!client.finishConnect()) {
62+
Thread.sleep(10);
63+
}
64+
65+
try (ObjectOutputStream objOut = new ObjectOutputStream(Channels.newOutputStream(client))) {
66+
objOut.writeObject(new MyObject("Test User", 25));
67+
}
68+
}
69+
70+
MyObject received = future.get(2, TimeUnit.SECONDS);
71+
assertEquals("Test User", received.getName());
72+
assertEquals(25, received.getAge());
73+
executor.shutdown();
74+
}
75+
}
76+
}

0 commit comments

Comments
 (0)