Networking in Java
Networking in Java
Networking in Java
Java
1
Objectives:
A computer network is an
interconnected collection of
autonomous computers.
3
What a Network Includes
A network includes:
Special purpose hardware
devices that:
Interconnect transmission media
Control transmission of data
Run protocol software
4
Addressing and Routing
6
Conti …
7
Two types of Communication
Connection-oriented
Setup the link before communication.
Similar to the phone call. We need the phone
number and receiver.
Example:- TCP (Transmission Control Protocol)
Connectionless
No link needed to be set up before
communication.
Similar to send a letter. We need the address and
receiver.
Example:- UDP (User Datagram Protocol)
8
TCP/IP
12
TCP Standard Ports
21 FTP
23 Telnet
80 HTTP
11
POP3
0
11
NNTP
9
13
TCP Protocol
14
15
Network Programming
18
Network Programming in java
21
TCP
Connections
in Java
22
TCP Protocol
There is a server process P2 and a client process P1.
P1 and P2 establish a communication line between
them using TCP sockets. P1 reads a message from
the user and places that message on the socket.
24
Cont…
28
Cont…
32
Cont…
Creating socket
Socket client = new
Socket(“www.microsoft.com", 80);
Note that the Socket constructor attempts to
connect to the remote server - no separate
connect() method is provided.
Data is sent and received with output and input
streams.
The Socket class has the following methods,
that retruns InputStream and the
OutputStream for reading and writing to the
socket
33
Cont…
35
The java.net.ServerSocket
class
try {
serverSocket = new
ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on
port: 4444"); System.exit(-1);
}
If the server successfully connects to its
port, then the ServerSocket object is
successfully created and the server continues to
the next step - accepting a connection from a
client:
38
Cont…
close everything.
Connectionles
s
communicatio
n
UDP
44
introduction
47
UDP Sockets (Datagram
Sockets)
49
Cont…
The java.net.DatagramSocket
class:
Constructor for sending:
public DatagramSocket()
51
Cont…
Notes:
After receiving, use the getPort() and
getAddress() on the received packet
to know where the packet came from.
Also use getData() to retrieve the data,
and getLength() to see how many
bytes were in the data
The received packet could be truncated
to fit the buffer
53
Using UDP in Java
(Datagrams)
Same mechanism for client AND server.
• To RECEIVE data:
– Create a DatagramSocket with port.
– Create a DatagramPacket.
– Receive the data through Socket into
the Packet.
54
Cont…
• To SEND data:
– Create DatagramSocket with address
and port.
– Create DatagramPacket.
– Fill Packet with Data.
– Send Packet through Socket.
55
Cont…
56
Multicast Sockets