Nearby lessons
78 of 125Java - Socket Programming
- How two programs on different computers talk to each other
- The client-server model
- Socket programming with ServerSocket and Socket
- The difference between TCP and UDP
- The InetAddress class
Socket Programming is a core concept of the Java language. This lesson explains Server Side — ServerSocket, Client Side — Socket and A Simple Two-Way Chat Program with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Server Side — ServerSocket
A server program creates a ServerSocket, tells it which port to listen on, and waits. When a client connects, the server gets a Socket to talk to that particular client.
Client Side — Socket
Run order matters: start the server first, then the client. The client new Socket("localhost", 9999) connects to the server on this same machine (localhost) at port 9999.
A Simple Two-Way Chat Program
Now let us make both sides talk: the client sends a message and the server replies.
- Networking = programs on different computers exchanging data.
- Client asks for a service; server provides it.
- Server uses ServerSocket (accept) ; client uses Socket (connect).
- TCP is reliable and ordered; UDP is fast but not guaranteed.
- IP address finds the computer, port number finds the service.
- InetAddress works with IPs; URL works with web addresses.
- Modern apps use REST APIs over HTTP, but sockets teach the core idea.
🧠 Test Your Knowledge
2 QuestionsFinished this lesson?
Mark it as complete to track your progress and see technology completion stats.