Skip to content

Commit 1be4a5d

Browse files
committed
Block when negotiating protocol
1 parent 7da794e commit 1be4a5d

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketClient.java

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,6 @@ public void start()
7070
{
7171
logger.debug( "~~ [CONNECT] %s:%d.", host, port );
7272
channel = ChannelFactory.create( host, port, config, logger );
73-
7473
protocol = negotiateProtocol();
7574
reader = protocol.reader();
7675
writer = protocol.writer();
@@ -170,21 +169,38 @@ private SocketProtocol negotiateProtocol() throws IOException
170169
{
171170
logger.debug( "~~ [HANDSHAKE] [0x6060B017, 1, 0, 0, 0]." );
172171
//Propose protocol versions
173-
ByteBuffer buf = ByteBuffer.allocate( 5 * 4 ).order( BIG_ENDIAN );
172+
ByteBuffer buf = ByteBuffer.allocateDirect( 5 * 4 ).order( BIG_ENDIAN );
174173
buf.putInt( MAGIC_PREAMBLE );
175174
for ( int version : SUPPORTED_VERSIONS )
176175
{
177176
buf.putInt( version );
178177
}
179178
buf.flip();
180179

181-
channel.write( buf );
180+
//Do a blocking write
181+
while(buf.hasRemaining())
182+
{
183+
if (channel.write( buf ) < 0)
184+
{
185+
throw new ClientException(
186+
"Connection terminated while proposing protocol. This can happen due to network " +
187+
"instabilities, or due to restarts of the database." );
188+
}
189+
}
182190

183-
// Read back the servers choice
191+
// Read (blocking) back the servers choice
184192
buf.clear();
185193
buf.limit( 4 );
186194

187-
channel.read( buf );
195+
while(buf.hasRemaining())
196+
{
197+
if ( channel.read( buf ) < 0 )
198+
{
199+
throw new ClientException(
200+
"Connection terminated while negotiating protocol. This can happen due to network " +
201+
"instabilities, or due to restarts of the database." );
202+
}
203+
}
188204

189205
// Choose protocol, or fail
190206
buf.flip();
@@ -223,7 +239,6 @@ public static ByteChannel create( String host, int port, Config config, Logger l
223239
SocketChannel soChannel = SocketChannel.open();
224240
soChannel.setOption( StandardSocketOptions.SO_REUSEADDR, true );
225241
soChannel.setOption( StandardSocketOptions.SO_KEEPALIVE, true );
226-
227242
soChannel.connect( new InetSocketAddress( host, port ) );
228243

229244
ByteChannel channel;

0 commit comments

Comments
 (0)