Socket

Module 2. Java Core
Level 19 , Lesson 0
Available

"Hi, Amigo!"

"Hello, Rishi!"

"The topic of today's lesson is sockets."

"You already know that every computer on the network has its own unique IP address."

"Yep."

"Now imagine you have several computers, each running a dozen programs that access the Internet: Skype, ICQ, etc."

"And these programs want to communicate with each other."

"We need to stop them from interfering with one another. We need to make it so Skype connect with Skype, Slack connects with Slack, etc."

"Remember how this problem was solved with URLs and web servers?"

"Yeah, we added ports."

"Exactly."

"It's just like making a bunch of small rooms in a house and saying that the house is an apartment building. Each port is like a separate apartment."

"If an IP address is a unique identifier for a computer, then an IP address combined with a port is a unique identifier for a certain 'apartment' in the computer, where a program can reside."

"This unique location is called a socket."

"A socket has its own unique number that consists of an IP address and a port number."

"Ah. In other words, a socket is an identifier for some virtual computer location where a program can reside? And another program sends messages to this location, which lets the two programs communicate?"

"I don't know how you understood that, but that is exactly right."

"My robo-sense told me."

"Great. Then let me give you some details."

"Sockets are actually the most basic and primitive way for programs to communicate."

"Java has two classes for working with sockets. They are Socket and ServerSocket."

"ServerSocket is a special class whose objects represent the server, i.e. they let me service requests that arrive on a particular socket."

"The Socket class is actually a client socket. We use it to send messages to another socket and receive the responses."

"Here's how to send a message to a socket:"

Example
// Create a socket
Socket clientSocket = new Socket("localhost", 4444);

// Get an OutputStream
OutputStream outputStream = clientSocket.getOutputStream();
PrintWriter out = new PrintWriter(outputStream, true);
out.println("Kiss my shiny metal ass!");
out.flush();

// Read the response
InputStream inputStream = clientSocket.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String answer = in.readLine();

"It's all very similar to downloading a file from the Internet."

"That, my boy, is because sockets are used there too."

"Sockets lie at the heart of everything associated with a network — well, almost everything."

"You can read additional information here"

"Thanks for the lesson, Rishi."

"I'm not done yet. That's wishful thinking."

"Now we'll explore how a server socket works."

"It's a bit more complicated."

Example
// Create a server socket object
ServerSocket serverSocket = new ServerSocket(4444); // Port

// Process incoming connections in a loop
while (true)
{
 // The accept method waits for someone to connect
 Socket socket = serverSocket.accept();

 // Read the response
 InputStream inputStream = socket.getInputStream();
 BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
 String message = in.readLine();

 // Create a response - we'll just reverse the string
 String reverseMessage = new StringBuilder(message).reverse().toString();

 // Send the response
 OutputStream outputStream = socket.getOutputStream();
 PrintWriter out = new PrintWriter(outputStream, true);
 out.println(reverseMessage);
 out.flush();
}

"I want to draw your attention to a couple of points."

"Point 1: To create a (client) socket, you need to specify an IP address (or domain name) and port. To create a server socket, you only need to specify a port. The server socket only exists on the computer where it was created."

"Point 2: The ServerSocket class has an accept() method that waits for an incoming connection. In other words, the method will run forever until some client socket tries to connect. Then the accept() method accepts the connection, creates a socket object to allow communication, and then returns this object."

"From a Java programmer's point of view, a socket is two streams: an InputStream from which you read messages/data, and an OutputStream to which you write messages/data."

"When you create a server socket, you're actually making a port that client sockets on other computers can connect to. But to do this, they must correctly specify the port number of our socket and the IP address of our computer. Well, or its domain name."

"Here's an interesting example for you. You can try digging into it and running it:"

https://www.logicbig.com/tutorials/core-java-tutorial/http-server/http-server-basic.html

"The whole point there is to use a server socket to write a super primitive web server that you can access simply from a browser."

"Wow! A web server? Cool! I'll study it very carefully."

"Thank you, Rishi."

"That's all, Amigo. Go relax!"

Comments (2)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Abhishek Tripathi Level 72, Rewa, India Expert
11 December 2023
In Java, when you're working with ObjectInputStream and ObjectOutputStream in a client-server communication scenario, there is a specific order in which you should initialize these streams. This order is crucial to prevent potential deadlock issues. The reason for this is related to how these streams handle headers and initialization. When an ObjectOutputStream is created, it writes a header to the underlying stream. The corresponding ObjectInputStream expects to read this header during its initialization. If you create the ObjectInputStream before the ObjectOutputStream on the other side, it may result in a deadlock.
MaGaby2280 Level 41, Guatemala City, Guatemala
3 August 2021
"I don't know how you understood that, but that is exactly right."😅😆🤣