williamboxhall / tcp-sockets Goto Github PK
View Code? Open in Web Editor NEWTCP Socket programming with Java
TCP Socket programming with Java
Hi. First of all congrats on getting the job :)
There's one problem with your solution though - you're handling all user clients through blocking sockets in a single thread. That works well for provided test script, but won't work well if one of the clients decides to send his id with some delay (or won't send it at all).
Consider the following use case:
telnet localhost 9099
(that connects a user client without sending his id)followermaze.sh
)You'll see that the first client (telnet) is preventing the others from connecting, and you'll see an error messages from test script after 20s deadline.
The bottom line is: one should not use blocking sockets with blocking operations in a single thread in a loop. Please look at these slides to see how it could be done. Slide 5 ("Classic ServerSocket Loop") shows how to handle your case (blocking sockets). The simplest fix would be to replace this line with something like this (Java 8):
new Thread(() -> router.connect(integerFrom(client), client)).start();
Although it might be a better idea to use ThreadPoolExecutor
instead. It's also probably a good idea to set SO_TIMEOUT
so that the client has some limited time for sending his id. Finally any exception in "client handler" should close the client connection and remove it from router's registry.
Best regards and see you soon :)
Tomasz
You did the impossible, you made Java code beautiful :)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.