rahul8590 71 Posting Whiz

Hello everyone , i am trying to create a multi threaded web server, i did the basic part (socket programming ) successfully .

Ref: http://www.daniweb.com/code/snippet217312.html

now , the next step , i am trying to establish it by making it multi thread or repetetive polling for client request (yet to decide)

The problem i am facing , is i want to create a shared memory pool where the client can access the list of files in the server.

Example :
There exist a folder named share and there exist some files , in it.
Now , if client request to access the files , it server has to find the file and then send it to the client .
Is it possible ? if yes , could u enlighten me on how to implement it.

Dani AI

Generated

— a practical path: keep the server protocol tiny, use a thread pool, and avoid shared mutable state unless you need a cache for performance.

Start simple

  • For correctness and simplicity, list the share folder on each LIST request (using File or Files.list) and stream files on demand for GET. This avoids concurrency bugs and stale state.
  • Use a fixed thread pool instead of creating a thread per socket: ExecutorService pool = Executors.newFixedThreadPool(N); — it bounds resources and prevents thread explosion.

Minimal protocol example (text-based)

Client -> Server: LIST
Server -> Client: file1.txt
Server -> Client: file2.jpg
Server -> Client: .
Client -> Server: GET file1.txt
Server -> Client: OK 12345
<raw 12345 bytes>

Design responses so the client knows file size (or use delimiters) and always check/read exactly that many bytes.

If you need a shared in-memory index

  • Keep the index immutable and swap references atomically (AtomicReference<List<FileMeta>>) so readers never block writers.
  • Update the index with java.nio.file.WatchService when files change, or refresh periodically. Use thread-safe containers (ConcurrentHashMap or copy-on-write lists) only when writes are rare.

Security, robustness, and ops

  • Prevent path traversal: compare canonical paths and restrict to the allowed root.
  • Enforce timeouts and max concurrent transfers, validate filenames, cap file size, and use try-with-resources to close sockets/streams.
  • Log transfers and test with concurrent clients; simulate mid-transfer deletes and network interruptions.

If you plan to serve many clients or want standard behavior, consider using an existing HTTP library (com.sun.net.httpserver or a light web server) rather than crafting your own protocol.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.