Implementing A Server: Submitted To:-Ms. Annu Dhankar Submitted By: - Chuni Lal Kukreja
Implementing A Server: Submitted To:-Ms. Annu Dhankar Submitted By: - Chuni Lal Kukreja
Submitted To:-
Ms. Annu Dhankar
Submitted By:-
Chuni Lal Kukreja
Connect With The Outside
World
Java program can reach out & touch a
program on another machine.
All low level networking details are
taken care of by classes in the java.net
package.
Big benefit of java is sending & receiving
data over a n/w is just I/O.
What We Have To Do ?
We have to make
Client Socket
Server Socket
Client & Server.
And make them communicate with
each other.
Overview
Client has to know about the
server.
Server has to know about it’s
client's.
Client A
Server
Client B
3 Things To Learn
How to establish the initial
connection b/w client & server.
How to send message b/w client &
server.
How to receive message from & to
client & server.
Make a Network Socket
Connection for Client
2 things are must to know about the server
-> Who it is (URL=“127.0.0.1”)
-> What port it’s running on (Port=5000)
To connect to another m/c, we need a socket
connection.
Socket sock = new Socket(“127.0.0.1”,5000);
To Read Data From A Socket
We use streams once socket connection is
made from client to server.
Client Server
String s=reader.readLine();
Close the open stream
reader.close();
Converted to bytes
characters from server
chained to chained to
Buffered
Client characters 011011011
Characters
destination InputStreamReader
source
Program to Receive Message
From Server
import java.io.*;
import java.net.*;
Acts as a bridge, it chains with Here socket gives us the low level
socket o/p stream, we can write conn stream & we chain it to the
Strings to socket connection PrintWriter, by giving it to its
constructor
contd….
Write (print) something
writer.println(“msg to send”);
It adds a new line at the end of what it sends
PrintWriter destination
Making Server To Interact
With Client
Server application makes a
ServerSocket , on a specific port.
ServerSocket serversock= new
ServerSocket(5000);
This starts the server app listening for client requests coming
in for port 4242
4242
Client Server
Client Server
5000
Server makes a new socket to
communicate with the client.
Socket sock= serversock.accept();
Accept() method blocks while its waiting for client Socket Connection.
When a client tries to connect the method returns a Socket (on
different port). So by this ServerSocket wait for other client request.
Client & Server Interaction
5000Server socket
Socket (waiting for next client)
Client Server
2589
Program to Send Message to
Client
import java.io.*;
import java.net.*;