Lab Socket Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

LAB: JAVA SOCKET PROGRAMMING

Java Socket programming is used for communication between the applications running on
different Java Runtime Environment (JRE). On the whole, a socket is a way to establish a
connection between a client and a server.

Java Socket programming can be connection-oriented or connection-less. Socket and


ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.

I. What is Socket Programming in Java?


Socket programming is a way of connecting two nodes on a network to communicate with
each other. One socket (node) listens on a particular port at an IP, while other socket reaches
out to the other in order to form a connection.

Socket API
The server forms the listener socket while the client reaches out to the server.
II. Socket Class

A socket is simply an endpoint for communications between the machines. The Socket class
is used to communicate client and server. The Socket class can be used to create a socket.

Important methods

III. ServerSocket Class


The ServerSocket class can be used to create a server socket. A ServerSocket which waits
for the client requests (when a client makes a new Socket()). After the successful connection
of a client and a server, it returns the instance of Socket at server-side.

Important methods

IV. Server Side Programming

Basically, the server will instantiate its object and wait for the client request. Once the client
sends the request, the server will communicate back with the response.
In order to code the server-side application, we need to follow the below-mentioned
steps.

1. Connection
We need to create the instance of ServerSocket class and bind it to a specific port number.
The accept() method of the ServerSocket instance waits for a client and returns an instance
of Socket if a client connects with the given port number.
Recall that a port number is a number that represents which application should run on a
server.

1. ServerSocket ss=new ServerSocket(3333);

2 Socket s=ss.accept(); //Listens for a connection from the client and accepts it

Here, we are using 3333 port number for the communication between the client and server.
You may also choose any other port number.

2. Communication
In order to communicate over a socket connection, streams are used for both input and output
the data.

3. Close the Connection


It is important to close the connection by closing the ServerSocket , socket and input/output
streams once everything is done.

NB. The step 2 can be repeated many times depending on the protocol agreed between the
server and the client. The steps 1 to 3 can be repeated for each new client.

V. Client Side Programming

In the case of client-side programming, the client will first wait for the server to start. Once
the server is up and running, it will send the requests to the server. After that, the client will
wait for the response from the server. So, this is the whole logic of client and server
communication.

In order to initiate a client’s request, you need to follow the below-mentioned steps:
1. Establish a Connection
The very first step is to establish a socket connection. A socket connection implies that the
two machines have information about each other’s network location (IP address or hostname
of the server) and port number.

Socket s=new Socket("localhost",33333);

or

Socket s= new Socket(“127.0.0.1”, 3333)

Here,
 for the first argument , we are using "localhost" or “ 127.0.0.0” because our server is
running on same system.
 the second argument represents the port number, i.e., 3333

2. Communication

In order to communicate over a socket connection, streams are used for both input and
output the data.

3. Closing the connection

It is important to close the connection by closing the socket as well as input/output streams
once everything is done.

Example of Java Socket Programming (Read-Write both side)

In this example, client will write first to the server and then server will receive and print the
text. Then, server will write to the client and client will receive and print the text. The step
goes on.
File: MyServer.java
import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}
File: MyClient.java
import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}

dout.close();
s.close();
}
}
[The flush method is invoked to write any buffered output to the underlying stream.]

[The Java Runtime Environment (JRE) is software that Java programs require to run
correctly. Java is a computer language that powers many current web and mobile
applications. The JRE is the underlying technology that communicates between the Java
program and the operating system.]

[The accept() call is used by a server to accept a connection request from a client. When a
connection is available, the socket created is ready for use to read data from the process that
requested the connection. The call accepts the first connection on its queue of pending
connections for the given socket socket.]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy