Nearby lessons
78 of 125Java - Socket Programming
📌 What You Will Learn
- 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.
In simple words: `ss.accept()` makes the server stop and wait until a client knocks. Nothing after that line runs until a client connects — which is why you must start the server before the client.
Example01
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.
Example02
A Simple Two-Way Chat Program
Now let us make both sides talk: the client sends a message and the server replies.
Trainer's Note: Modern note: raw socket programming is the foundation, but today most applications talk over the web using HTTP with REST APIs (sending JSON data) rather than raw sockets. For learning networks and exams, sockets are essential. For real projects, learn REST APIs and Spring Boot. The socket idea — client asks, server answers — is the same in both.
Example03
📝 Key Takeaways
- 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 QuestionsProgress: 0 / 2