0% found this document useful (0 votes)
9 views9 pages

Socket Programming

The document provides an overview of socket programming concepts, including IP addresses, ports, and the establishment of server-client connections. It details the architecture of a server handling multiple clients, including authentication flows, file upload/download protocols, and message management systems. Additionally, it covers concurrency, threading, and HTTP basics relevant to the exam context.

Uploaded by

Ijs Asif
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views9 pages

Socket Programming

The document provides an overview of socket programming concepts, including IP addresses, ports, and the establishment of server-client connections. It details the architecture of a server handling multiple clients, including authentication flows, file upload/download protocols, and message management systems. Additionally, it covers concurrency, threading, and HTTP basics relevant to the exam context.

Uploaded by

Ijs Asif
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Socket programming

Socket Programming — Exam Tutorial


CSE 322 | Based on Assignment-1 & Lecture Slides

1. Core Networking Concepts (Quick Review)


IP Address
Uniquely identifies a machine in a network.
A machine connected to multiple networks gets a different IP per network interface
(e.g., one IP for Ethernet, another for WiFi).
Number of active network interfaces = number of IP addresses on that device.

Port
An endpoint/channel for communication for different programs on the same machine.
Total: 2¹⁶ = 65536 ports (some are reserved, e.g., 80 for HTTP, 443 for HTTPS).
A process must acquire a port before doing network communication.
Use netstat to see ports in use.

Socket
Represents a single connection between two network applications.
Number of active connections = number of sockets.
A socket needs to know:
Remote IP
Remote Port
Local Port
A socket has an input buffer and output buffer for reading/writing.

Socket vs Port
Multiple sockets can share the same local port (e.g., a server on port 6666 has a
separate socket per connected client — all on port 6666).
But only one program can bind to a port at a time.
2. How a Server-Client Connection is Established (Step by
Step)
This is the core concept — understand this flow deeply.

Step 1: Server opens a ServerSocket on a port (e.g., 6666) and starts


listening.

Step 2: Client connects to (Server IP, 6666).

Step 3: Server calls accept() → creates a new dedicated Socket for that
client.

Step 4: Both sides now have their own Socket object.


Server-side socket knows: Client's IP + Client's ephemeral port (e.g.,
50320)
Client-side socket knows: Server's IP + Server's port (6666)

Step 5: Server keeps its ServerSocket listening for NEW connections


while handling the current client on a separate thread.

Step 6: Multiple clients can connect simultaneously.


Each gets their own socket on the server side (all bound to port 6666,
but distinguished by the client's different remote port/IP).

Underlying protocol: TCP (Transmission Control Protocol) — reliable, ordered delivery.

3. Assignment-1 System Architecture


The Big Picture
Server runs continuously on PORT 6666, accepting client connections.
Each connected client gets its own ClientHandler thread.
Clients communicate with the server using serialized Java objects ( ObjectInputStream /
ObjectOutputStream ).
Server maintains several global maps (shared across all threads):
onlineClients — currently connected clients (username → ClientHandler)
knownClients — all clients ever connected (username → Boolean)
fileMetadata — metadata for all uploaded files (fileId → FileMetadata)
activeRequests — pending file requests (requestId → FileRequestRecord)
Server Configurable Parameters

Parameter Value Meaning


PORT 6666 Server listens here
MAX_BUFFER_SIZE 10 MB Total size limit of chunks in buffer
MIN_CHUNK_SIZE 64 KB Minimum chunk size for upload
MAX_CHUNK_SIZE 512 KB Maximum chunk size; also used for download

4. Authentication Flow
1. Client connects → server creates ClientHandler thread.
2. Client sends a LoginRequest(username) object.
3. Server checks:
Is username already online? → Deny ( LoginResponse(false, "Username already
taken.") )
Is username new? → Create a directory server_storage/<username>/ , create
[Link] , [Link] , [Link] .
Username known but offline? → Allow login.
4. Server sends LoginResponse(true, "Login successful. Welcome <username>!") .
5. Client is added to onlineClients map.

Key rule: Two clients cannot use the same username simultaneously. The connection is
terminated immediately on failure.

5. Client Capabilities & Request Types


After login, the client sends Request objects and receives Response objects. The dispatch
happens in handleRequest() .

# Request Class Server Handler What It Does


1 GetClientsRequest handleGetClients() Returns all known
clients with
online/offline status
2 GetOwnedFilesRequest handleGetOwnedFiles() Returns client's own
uploaded files
# Request Class Server Handler What It Does
(public + private),
complete only
3 GetPublicFilesRequest handleGetPublicFiles() Returns other
clients' public
complete files
4 UploadFileRequest handleUploadFile() Initiates chunked file
upload
5 DownloadFileRequest handleDownloadFile() Server sends file in
MAX_CHUNK_SIZE
chunks, no ACK
needed
6 CreateFileRequestRequest handleCreateFileRequest() Client requests a file
by description;
server generates
request ID
7 GetMessagesRequest handleGetMessages() Returns unread
messages
8 GetHistoryRequest handleGetHistory() Returns
upload/download log
9 LogoutRequest handleLogout() Client logs out
gracefully

6. File Upload Protocol (Most Important — 15 Marks)


This is the most complex and heavily weighted part.

Phase 1: Initiation
1. Client sends UploadFileRequest(username, fileName, fileSize, accessType,
requestID) .
2. Server checks: currentBufferSize + fileSize > MAX_BUFFER_SIZE ?
Yes → Reject: Response(false, "Buffer full. Try again later") .
No → Continue.
3. If uploading in response to a file request:
requestID must be valid (in activeRequests ).
accessType must be "public" (forced).
4. Server:
Adds fileSize to currentBufferSize .
Generates a unique fileId (e.g., "F1" , "F2" , ...).
Randomly picks chunkSize in [MIN_CHUNK_SIZE, MAX_CHUNK_SIZE] .
Creates a FileMetadata entry with isComplete = false .
Sends UploadApprovedResponse(true, "Start upload", fileId, chunkSize) .

Phase 2: Chunked Transfer

For a 1040 KB file with chunkSize = 100 KB:


→ 10 chunks of 100 KB + 1 chunk of 40 KB = 11 chunks total

For each chunk:


Client sends chunk → Server receives → Server sends ACK → Client sends next
chunk

Stop-and-wait: client sends next chunk only after receiving ACK for current chunk.

Phase 3: Completion
1. After all chunks sent, client sends a completion message.
2. Server sums all received chunk sizes.
3. Total == declared fileSize ?
Yes → [Link](true) , send success response.
No → Send error, delete all chunks.

Disconnection Mid-Upload
If client goes offline during upload → server discards incomplete files (isComplete stays
false).
currentBufferSize should be decremented accordingly on cleanup.

7. File Download Protocol (10 Marks)


Much simpler than upload:

1. Client sends DownloadFileRequest(username, filePath, ownerName) .


2. Server sends the file in chunks of exactly MAX_CHUNK_SIZE (512 KB).
3. Server does NOT wait for ACK between chunks — just streams them.
4. Server sends a completion message when done.
5. History is logged on both upload and download.

8. File Request (Messaging) System (5 Marks)


1. Client sends CreateFileRequestRequest(username, description, recipient) .
recipient = specific username → unicast (send only to that client).
recipient = "ALL" → broadcast (send to all known clients, online or offline).
2. Server generates a requestId (e.g., "R1" ), stores it in activeRequests .
3. Online recipients receive the message immediately.
4. Offline recipients receive it when they next log in (stored in [Link] ).

When a file is uploaded against a requestId:

Server notifies the requester with a message.


Multiple people can fulfill the same request → multiple messages sent.

9. Message Management (4 Marks)


Each client has a [Link] file in their directory.
unreadMessages list is maintained in ClientHandler (in-memory).
GetMessagesRequest → server returns and clears unread messages.
Messages include: file request notifications + upload fulfillment notifications.

10. Upload/Download History Log (4 Marks)


Stored in server_storage/<username>/[Link] .
Each entry contains:
Filename
Date and Time (e.g., 2025-12-14 22:30:00 )
Action: UPLOAD or DOWNLOAD
Status: SUCCESS or FAILED

11. Concurrency & Threading


One thread per client ( ClientHandler extends Thread ).
ConcurrentHashMap used for all shared data structures — thread-safe.
AtomicLong used for currentBufferSize , fileIdCounter , requestIdCounter — atomic
increment, no race condition.
synchronized (oos) used when writing to the output stream — prevents interleaved
writes.
Separate threads should also be used for parallel upload/download operations (as required
by assignment rule 10).

12. HTTP Basics (from slides — may appear in exam context)


URL Structure

[Link]
↑ host ↑port ↑ path (suffix)

Client uses prefix to find server (host + port).


Server uses suffix to locate the file/resource.

HTTP Request Format

<method> <uri> <version>


<header-name>: <header-value>
...
<blank line>
[body]

Common methods: GET (retrieve), POST (send data), PUT (write file), DELETE (delete file),
HEAD (like GET, no body).

HTTP Response Format

<version> <status-code> <status-msg>


<header-name>: <header-value>
...
<blank line>
[body]

Common status codes: 200 OK , 403 Forbidden , 404 Not Found .


HTTP/1.0 vs HTTP/1.1

Feature HTTP/1.0 HTTP/1.1


Connection New connection per request Persistent ( Keep-Alive )
HOST header Not required Required
Caching support Basic Enhanced

Proxy
Acts as server to client and client to server.
Useful for: caching, logging, anonymization.
On cache hit: serves from local cache without contacting origin server.

13. Key Exam Q&A


Q: Why does the server use ObjectOutputStream before ObjectInputStream ? A: To avoid
deadlock — both sides must flush their output stream before the other can read. Creating OOS
first and flushing ensures the stream header is sent before blocking on OIS .

Q: Why is chunkSize randomly chosen per upload? A: The assignment requires it —


simulates variable network/server conditions. Range is [MIN_CHUNK_SIZE, MAX_CHUNK_SIZE] .

Q: What happens if declared file size doesn't match received chunks? A: Upload fails —
server sends error and deletes all chunks. The file is never marked complete.

Q: Can a private file be downloaded by others? A: No. handleGetPublicFiles() only


returns files where isPublic == true AND owner != requesting client . Private files are
completely hidden from others.

Q: What makes a file request upload special? A: The uploader must (a) provide a valid
requestID and (b) the file is automatically forced to public access type. The requester gets a
notification message on completion.

Q: How does the server handle a client that disconnects mid-transfer? A: The server
should detect the disconnection (exception on stream read/write), remove the client from
onlineClients , and discard any incomplete file (chunks accumulated so far).

Q: What is the difference between onlineClients and knownClients ? A: onlineClients


= currently connected right now. knownClients = everyone who has ever connected (persists
across sessions, used for offline messaging and directory management).
Good luck on the exam, Apurbo!

You might also like