Prac-1 JAVA

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

Network Programming and Java

Sockets

1
Elements of C-S Computing

a client, a server, and network

e
st qu
Re
Client
Server
Network
Re
lt su

Client machine
Server machine

2
Networking Basics

• Applications Layer • TCP/IP Stack


– Standard apps
• HTTP
• FTP Application
• Telnet (http,ftp,telnet,
– User apps
• Transport Layer
…)
Transport
– TCP (TCP, UDP,..)
– UDP
– Programming Interface:
Network
• Sockets (IP,..)
• Network Layer Link
– IP
• Link Layer (device
– Device drivers driver,..)
3
Networking Basics
• TCP (Transport Control • TCP/IP Stack
Protocol) is a
connection-oriented Application
protocol that provides a (http,ftp,telnet,
reliable flow of data …)
Transport
between two computers. (TCP, UDP,..)
• Example applications: Network
– HTTP (IP,..)
– FTP Link
– Telnet (device
driver,..)
4
Networking Basics
• UDP (User Datagram • TCP/IP Stack
Protocol) is a protocol
that sends independent Application
packets of data, called (http,ftp,telnet,
datagrams, from one …)
Transport
computer to another (TCP, UDP,..)
with no guarantees about Network
arrival. (IP,..)
• Example applications: Link
– Clock server (device
– Ping driver,..)
5
Understanding Ports
P
• The TCP and UDP server o TC
r P Client
protocols use ports to
map incoming data to t
a particular process
running on a
computer. app app app app

port port port port


TCP or UDP
Packe
6
Dat t
port# data
Understanding Ports
• Port is represented by a positive (16-bit) integer
value
• Some ports have been reserved to support
common/well known services:
– ftp 21/tcp
– telnet 23/tcp
– smtp 25/tcp
– login 513/tcp
• User level process/services generally use port
number value >= 1024
7
Sockets and Java Socket Classes

• A socket is an endpoint of a two-way


communication link between two programs
running on the network.
• A socket is bound to a port number so that
the TCP layer can identify the application
that data destined to be sent.
• Java’s .net package provides two classes:
– Socket – for implementing a client
– ServerSocket – for implementing a server
8
Java Sockets
Server ServerSocket(1234)

Output/write stream Client

Input/read stream

Socket(“localhost”, 1234)
9
Implementing a Server
1. Open the Server Socket:
ServerSocket server;
DataOutputStream os;
DataInputStream is;
server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
is=new DataInputStream(client.getInputStream());
os=new DataOutputStream(client.getOutputStream());
4. Perform communication with client
Receive from client:
String line = is.readLine();
Send to client:
os.writeBytes("Hello\n");

5. Close sockets: client.close();


10
Implementing a Client
1. Create a Socket Object:
client = new Socket( server, port_id );
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream() );
os = new DataOutputStream( client.getOutputStream() );
3. Perform I/O or communication with the server:
– Receive data from the server:
String line = is.readLine();
– Send data to the server:
os.writeBytes("Hello\n");
4. Close the socket when done:
client.close();

11
Creating a server that sends data
import java.net.*;
import java.io.*;
public class SimpleServer {
public static void main(String args[]) throws IOException {
// Register service on port 1234
ServerSocket s = new ServerSocket(1234);
Socket s1=s.accept(); // Wait and accept a connection
// Get a communication stream associated with the socket
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream (s1out);
// Send a string!
dos.writeUTF("Hi there");
// Close the connection, but not the server socket
dos.close();
s1out.close();
s1.close();
}
} 12
Creating a client that receives data
import java.net.*;
import java.io.*;
public class SimpleClient {
public static void main(String args[]) throws IOException
{ // Open your connection to a server, at port 1234
Socket s1 = new Socket(“localhost",1234);
// Get an input file handle from the socket and read the input
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = new String (dis.readUTF());
System.out.println(st);
// When done, just close the connection and exit
dis.close();
s1In.close();
s1.close();
}
}

13
Run
• Run Server
– java SimpleServer

• Run Client on any machine


– java SimpleClient

Hi there

14
Practical 1
Aim : Implement Concurrent echo client-server application in Java

• TCP SERVER:
• This Java program implements a simple TCP server that listens for
client connections on port 8088 and echoes back messages sent by the
client with a "Hello:" prefix.

• import java.io.*; // This package provides classes for system input and
output through data streams, serialization, and the file system.

• import java.net.*; // This package provides classes for implementing


networking applications.
Practical 1
Aim : Implement Concurrent echo client-server application in Java

• public class TcpServer // Defines the main class for the TCP server.
• {
• public static void main(String[] args) throws Exception
• // The main method which serves as the entry point for the program. It declares
that it can throw an Exception.
• { // Setting Up the Server
• ServerSocket ss=new ServerSocket(8088); // Creates a server
socket that listens on port 8088.
• System.out.println("server is ready!"); // Prints a message indicating
that the server is ready to accept connections.
• Socket ls=ss.accept(); // Accepting Client Connections. Waits for a
client to connect and accepts the connection, creating a new socket for
communication with the client.
Practical 1
Aim : Implement Concurrent echo client-server application in Java

• //Handling Client Communication


• while (true) // A loop that runs indefinitely to handle continuous client
communication.
• {
• System.out.println("Client Port is " + ls.getPort()); // Prints the port
number of the connected client.
• // Reading Data from Client
• InputStream is=ls.getInputStream(); // Gets the input stream of the
connected client socket to read data.
• byte data[]=new byte[50]; // Creates a byte array of size 50 to store
incoming data.
• is.read(data); // Reads data from the client into the byte array.
• String mfc=new String(data); // Converts the byte array into a string.
Practical 1
Aim : Implement Concurrent echo client-server application in Java

• //mfc: message from client


• mfc=mfc.trim(); // Trims any leading and trailing whitespace from the
received message.
• // Preparing and Sending Response to Client
• String mfs="Hello:"+mfc; // Prepares a response message by
prefixing "Hello:" to the received message.
• //mfs: message from server
• //SENDING MSG TO CLIENT
• OutputStream os=ls.getOutputStream(); // Gets the output stream of
the connected client socket to send data.
• os.write(mfs.getBytes()); // Converts the response message to bytes
and sends it to the client.
• }
• }
• }
Practical 1
Aim : Implement Concurrent echo client-server application in Java

• The while (true) loop ensures that the server continuously reads messages from the
client and responds, without closing the connection.
• This server program accepts a client connection, reads a message from the client,
adds a "Hello:" prefix to the message, and sends it back to the client. This process
repeats indefinitely as long as the server is running and connected to the client.

• TCP CLIENT:
• This Java program implements a simple TCP client that connects to a
server on localhost at port 8088, sends a message to the server, and
receives a response.
• import java.io.*; // This package provides classes for system input and output
through data streams, serialization, and the file system.
• import java.net.*; // This package provides classes for implementing networking
applications.
Practical 1
Aim : Implement Concurrent echo client-server application in Java

• // Main Class and Method


• class TcpClient { // Defines the main class for the TCP client.
• public static void main(String[] args) throws Exception { // The main
method which serves as the entry point for the program. It declares that it can
throw an Exception.
• // Connecting to the Server
• System.out.println("connecting to server"); // Prints a message indicating that
the client is attempting to connect to the server.
• Socket cs = new Socket("localhost", 8088); // Creates a socket and connects it
to the server running on localhost at port 8088.

• // Setting Up Input from Console


• BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
• // Sets up a BufferedReader to read input from the console.
Practical 1
Aim : Implement Concurrent echo client-server application in Java

• // Displaying Connection Information


• System.out.println("The Local Port " + cs.getLocalPort() + "\nThe Remote Port" +
cs.getPort()); // Prints the local port number and the remote port number of the
connection.
• System.out.println("The Local socket is " + cs); // Prints the local socket
information.
• // Reading Input from User
• System.out.println("Enter your name"); // Prompts the user to enter their name.
• String str = br.readLine(); // Reads a line of text entered by the user.
• //Sending Data to Server
• OutputStream os = cs.getOutputStream(); // Gets the output stream of the socket to
send data to the server.
• os.write(str.getBytes()); // Converts the user input (name) to bytes and sends it to
the server.
Practical 1
Aim : Implement Concurrent echo client-server application in Java

• // Reading Data from Server


• InputStream is = cs.getInputStream(); // Gets the input stream of the socket to
receive data from the server.
• byte data[] = new byte[50]; // Creates a byte array of size 50 to store incoming
data.
• is.read(data); // Reads data from the server into the byte array.

• // Printing Server Response


• String mfs = new String(data); // Converts the byte array into a string.
• mfs = mfs.trim(); // Trims any leading and trailing whitespace from the received
message.
• System.out.println(mfs); // Prints the message received from the server to the
console.
• }
• }
Practical 1
Aim : Implement Concurrent echo client-server application in Java

• This client program connects to a server at localhost on port 8088, reads a name
from the console, sends the name to the server, receives a response from the
server, and prints the response.
• The server's response is expected to be prefixed with "Hello:" based on the server
code you provided earlier.

You might also like