Socket in Java
Socket in Java
There is a port number for each socket so that the TCP layer can identify
the application where to send the data.
1. Create a Socket
2. Connect it to ServerSocket by specifying the IP address and the port
number
3. Get the reference of the OutputStream
4. Attach this reference to OutputStreamWriter
5. Write and close
6. Get the reference of InputStream
7. Attach this reference to InputStreamWriter
8. Read and Buffer
9. Parse, interpret and process it
10.Close Connection
1. Creating a Socket
To create a Socket, we use the Socket class and create its object. We pass
the IP address and port number of the Server inside the Socket.
Here, we are using “localhost” because our server and the client
applications are present on the same machine. For example:
out.write();
out.close();
input.readLine();
input.close();
socket .close();
1. Create ServerSocket
2. Bind it to a port number
3. Put it into the listening mode
4. Get the reference of InputStream
5. Attach the reference to InputStreamReader
6. Read and buffer
7. Parse the request
8. Prepare response
9. Get the reference of OutputStream
10.Attach the reference to OutputStreamReader
11. Write the response
12. Close Connection
Note: The 4th point only happens when there is a request from the client.
Otherwise, the server ends at the 3rd stage only.
1. Creating a ServerSocket
To create a ServerSocket, we use the ServerSocket class and create its
object.
ServerSocket server;
server.accept();
socket .close();
package com.techvidvan.socketprogramming;
//A Java program for a Server Side
import java.net.*;
import java.io.*;
public class ServerSide
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
//constructor with port
public ServerSide(int port)
{
//starts server and waits for a connection
try
{
System.out.println("Server started at port 5100");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
//takes input from the client socket
in = new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
String line = " ";
//reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
//close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[]){
ServerSide server = new ServerSide(5100);
}
}
Output:
Server started at port 5230
Waiting for a client … Commented [U1]:
package com.techvidvan.socketprogramming;
//A Java program for a ClientSide
import java.net.*;
import java.io.*;
public class ClientSide
{
//initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
//constructor to put ip address and port
@SuppressWarnings("deprecation")
public ClientSide(String address, int port)
{
//establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected");
//takes input from terminal
input = new DataInputStream(System.in);
//sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
// string to read message from input
String line = " ";
//keep reading until "Over" is input
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
//close the connection
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
ClientSide client = new ClientSide("localhost", 5230);
}
}
Output:
Connected
Important Points
The server application makes the object of ServerSocket on port number
5230. Then, the server starts listening for client requests for port 5230.
After that, the Server makes a Socket object to communicate with the
client.
The accept() method does not run unless the client program connects to
the server.
The getInputStream() method takes the input from the socket.
The Server keeps receiving messages until the Client sends “Over”.
In the end, we close the connection with the close() method. We close
both the socket and the input stream.
Compile both the Client and Server programs on your machine, and
then, first, run the Server and then run the Client.