Advanced Java Programming · Unit 7
Network Programming with Sockets
Exam-focused notes for Network Programming with Sockets (Advanced Java Programming, BIT401): what the TU syllabus asks and how it has actually been tested, with 5 solved past questions from this unit.
Network Programming with Sockets in short
Network programming lets two programs on different computers exchange data. Java does this with sockets, using the TCP and UDP protocols.
What this unit covers
- TCP socket programming steps
- UDP socket programming steps
- Client-server communication
- Port usage and significance
- Socket creation and connection
- Data transmission over sockets
TCP socket programming steps
2082 · 5 marks
Mention the steps to write the socket program using TCP. [5]
Show solved answerHide answer
Model Answer: Steps to Write a Socket Program Using TCP
Since reference notes are not provided, this answer follows standard TCP socket programming methodology taught in BSc CSIT curricula:
Server-Side Steps:
-
Create a Socket
- Use
socket()system call to create a socket with domain (AF_INET), type (SOCK_STREAM), and protocol (0 or IPPROTO_TCP)
- Use
-
Bind the Socket
- Use
bind()to associate the socket with a specific port number and IP address - Define server address structure with port and address family
- Use
-
Listen for Connections
- Use
listen()to mark the socket as passive and specify the backlog queue size for pending connections
- Use
-
Accept Client Connection
- Use
accept()to accept incoming client connections - Creates a new socket for communication with the connected client
- Use
-
Send/Receive Data
- Use
send()orwrite()to transmit data to the client - Use
recv()orread()to receive data from the client
- Use
-
Close the Socket
- Use
close()to terminate the connection and release resources
- Use
Client-Side Steps:
-
Create a Socket
- Use
socket()with same parameters as server
- Use
-
Connect to Server
- Use
connect()to establish connection to server's IP address and port
- Use
-
Send/Receive Data
- Use
send()orwrite()to send data to server - Use
recv()orread()to receive data from server
- Use
-
Close the Socket
- Use
close()to terminate connection
- Use
Key Point: TCP ensures reliable, ordered, connection-oriented communication between client and server.
2080 · 5 marks
Write a socket program using TCP where client sends an integer to server and server response whether it is positive or negative. [5]
0 · 5 marks
Write down a java program where client sends a number to server and server calculates its factorial and sends it back to client using TCP. [5]
UDP socket programming steps
2081 · 5 marks
Write the steps of writing socket program using UDP. [5]
Port usage and significance
2081 · 5 marks
Why do we need ports in socket programming? What types of instructions are written in try block? [5]
Make Unit 7 stick
Practice BIT401 with flashcards & quizzes