Introduction to Socket Programming in Java
The World Wide Web and Internet have changed the way we live and communicate with each other and the way we conduct science, engineering, and commerce. Modern life is completely being driven around or being centered around the Internet. Businesses continuously seek new ways to produce and communicate with various services in a new fashion introducing innovation. In this article, we will discuss Socket Programming in Java.
Sockets provide an interface for programming networks of the transport layer of the OSI model. Network communications using sockets are found ubiquitously throughout the Internet. In addition to that, a socket program written in Java can communicate with a socket program written in a non-Java language like C, C++, Python, etc.
Socket Class Methods
Socket Class methods are found in Java. A socket is bound to be a port number so that the TCP recognizes the port number in which the data is to be sent. Java provides a set of classes, one of which is java.net. This is used for the fast development of network applications. Key classes, interfaces, and exceptions that are present in the java.net package simplify the complexity involved in creating client and server programs are:
Classes are:
- Content Handler
- Datagram Packet
- Datagram Socket
- Datagram Socket Imp 1
- HTTP URL Connection
- I net address
- Multicast Socket
- Server Socket
- Socket
- Socket Imp 1
- URL
- URL Connection
- URL Encoder
- URL Stream Handler
Interfaces are:
- Content Handler Factory
- File Name Map
- Socket Impl Factory
- URL Stream Handler Factory
Exceptions are:
- Bind Exception
- Connect Exception
- Malformed URL Exception
- No Route To Host Exception
- Protocol Exception
- Socket Exception
- Unknown Host Exception
- Unknown Service Exception
TCP/IP Socket Programming
There are two classes used from the java.net package which are used in the creation of programs.
- Server Socket
- Socket
A server program communicates through input and output streams. If there is a connection request, then there is a new socket that comes into play, and here is a connection established with it.
Method 1 – Creating a Server Socket Program
There are various steps for creating a server socket program in Java.
The simple steps of creating a server socket program are as follows:
Step 1: The Socket Server is Opened.
Server Socket General= new Server Socket(PO)
Here PO is the port number.
Here the Port number is assigned to the server network through which it will communicate using Input/ Output streams.
Step 2: There is a Client Request for which we have to Patiently Wait.
Socket General= server. accept()
Here is the Server. accept() waits for the client, and the name of the socket is Client here.
Step 3: I/O Streams are Created so that a Connection is Established
Data Input Stream
is = new Data Input Stream(client. Get Input Stream());
Data Output Stream
os = new Data Output Stream(client. get Output Stream());
The input stream and the output stream are assigned their Get Input Stream(), and they are called respectively.
Step 4: Contact with the Client is Created.
Receive from client:
string hello = br. Read Line();
Send it to the client:
br. Write Bytes("How are you\n");
The following code communicates with the client receiving and sending to a client the requests.
Step 5: Finally, the Socket is made to Exit.
Finally, the close socket function is used to close and end the socket programming.
A simple example of a server socket is shown below:
A simple program for connecting the server.
Code:
import java.net.*;
import java.io.*;
public class SimpleMachine {
public static void main(String args[]) throws IOException {
// On port 1362 server port is registered
ServerSocket soc = new ServerSocket(1362);
Socket soc1=soc.accept(); // Link is accepted after waiting
// Linked with the socket there should be a connection
OutputStream s1out = soc1.getOutputStream();
DataOutputStream dosH = new DataOutputStream (s1out);
// A string command is sent
dosH.writeUTF("Hello how are you");
// The connection can be closed but the server socket cannot.
dosH.close();
s1out.close();
soc1.close(); }
}
Method 2 – Creating a Simple Server Socket Program
Now we are going to see a Simple Client Program in Java.
The steps for creating a simple client program in Java is shown below:
Step 1: Socket Object is Made.
Socket client= new Socket(server, port_id)
The server and the Port ID are connected; that is, the server is connected to the Port ID.
Step 2: Input/Output Streams are Created.
is = new Data Input Stream(client.getInputStream());
os = new Data Output Stream(client.getOutputStream());
The Input Stream is, and Output Stream os is used for communicating with the client.
Step 3: Input/Output streams are made for talking to the Client.
Data is read from the server:
string hello = br. readLine();
Send data to the server:
br.writeBytes("How are you\n")
This step communicates with the server. The input stream and output stream both communicates with the server.
Step 4: Close the Socket when done.
This function will close the client when it is finally done.
An example of a simple server socket program is shown below.
A simple program for the client.
Code:
import java.net.*;
import java.io.*;
public class SimpleMachineClient {
public static void main(String args[]) throws IOException
{
// At port 1325, connection to the server is opened
Socket s1H = new Socket("host",1325);
// Read the input stream by getting an input file from the socket
Input Stream s1I = s1. getInputStream();
Data Input Stream disH = new Data Input Stream(s1In);
String str = new String (disH.readUTF());
System.out.println(str);
// After it is done, we can close the connection.
disH.close();
s1I.close();
s1H.close();
}
}
Conclusion
Socket programming is beneficial in Java and in any other programming language. A program written in Java can connect with a program written in C or C++. In other words, the language of the socket program doesn’t matter when there has to be a connection between the two. In this article, we have basically seen the Simple Server and the Simple Client example where there is a connection between the server socket and in the other, there is a connection between the server socket. We have used TCP/IP programming for the same. However, there are a lot of programming techniques like UDP programming techniques and URL programming techniques. We have not seen examples of such in this article. We have stressed on TCP/IP programming technique.
Recommended Articles
This is a guide to Socket Programming in Java. Here we discuss Socket Class Methods with two classes used from the java.net package that is used in the creation of programs. You can also go through our other suggested articles to learn more –