Unit-1 - Java Networking
Unit-1 - Java Networking
GTU # 3160707
Unit-1
Java Networking
Output
IP: www.darshan.ac.in/89.238.188.50
Output
LocalHost: LAPTOP-NB4I63VB/10.254.3.79
Output
Hostname: LAPTOP-NB4I63VB
Output
HostAddress: 89.238.188.50
Output
Host Name: www.darshan.ac.in
IP Address: 89.238.188.50
http://10.255.1.1:8090/index.html
OR
URL obj=new URL(String protocol, String host, int port, String path) throws MalformedURLException
OR
URL obj=new URL(String protocol, String host, String path) throws MalformedURLException
Waits
Response
socket socket
Request
Server Client
running in a computer.
1010
Each computer is equipped with some ports.
80
The server connects with port. S
Ports
Computer where
5566 E
This process is called binding to a port. R
server is running
1080
The connection is called a server socket. V
2010 E
R
3040
The Java code for creating server in Network Programming:
extracted, and the loop again waits for the next Computer
client.
Now, we should make the server wait till a client accepts connection, this is done using accept()
method.
This object is used to establish communication with the clients
Socket s=ss.accept();
At client side, create socket with host name and port number using Socket class.
Use following formats for creating a object of Socket class.
Socket s=new Socket(String hostName, int port);
OR
Socket s=new Socket(InetAddress ipAddress, int port);
OutputStream obj=s.getOutputStream();
Create PrintStream object to send data into the socket
PrintStream ps=new PrintStream(obj);
Call print() or println() method to send data.
ps.println(str);
Close the connection.
ss.close(); //close ServerSocket
s.close(); //close Socket
ps.close(); // //close PrintStream
Prof. Rajkumar B Gondaliya #3160707 (AJP) Unit 1 – Java Networking 27
Creating a Client That Receiving Data
Create a Socket object with server address and port number
Socket s=new Socket(“localhost”,8070);
For receiving data attach input stream to the socket, using getInputStream() method
InputStream inStr=s.getInputStream();
To read the data from socket, we can take the help of BufferedReader
BufferedReader br=new BufferedReader(new InputStreamReader(inStr));
it creates a datagram socket and binds it with the given Port Number.
DatagramSocket ds=new DatagramSocket(int port,InetAddress ipAddress) throws SocketException
it creates a datagram socket and binds it with the specified port number and host address.
Output
Message: Message from Sender