Java
Networking
TCP
• TCP stands for Transmission Control Protocol
• TCP is connection‐oriented
• It provides reliability
• What is Server and Client?
– A server is a piece of software which advertises and then
provides some service on request
– A client is a piece of software (usually on a different
machine) which makes use of some service
Prepared By - Rifat Shahriyar 2
TCP Sockets
• Two types of TCP Sockets
• ServerSocket
– ServerSocket is used by servers so that they can accept
incoming connections from client
• Socket
– Socket is used by clients who wish to establish a
connection to a (remote) server
Prepared By - Rifat Shahriyar 3
Scenario
Client Server ([Link])
ServerSocket ss=new
ServerSocket(22222);
Socket s = new Socket
(“[Link]”, 22222); Socket cs = [Link]();
[Link](); [Link]();
[Link](); [Link]();
Prepared By - Rifat Shahriyar 4
TCP Sockets Code
• Packages:
– tcpsimple (no threading)
– tcpstring (multithreading, string send and receive)
– tcpobject (multithreading, object send and
receive)
– tcpdiff (multithreading, the server sends
messages to multiple clients)
– tcpforward (multithreading, the server forwards
messages between multiple clients)
Prepared By - Rifat Shahriyar 5
UDP
• UDP stands for User Datagram Protocol
• UDP is not connection‐oriented
• It does not provide reliability
• It sends and receives packets known as Datagram
Prepared By - Rifat Shahriyar 6
Datagram Packet & Socket
• One type of Packet and one type of Socket
• DatagramPacket
– Used to encapsulate Datagram
• DatagramSocket
– DatagramSocket is used by both server and client to
receive DatagramPacket
• Example: [Link], [Link]
Prepared By - Rifat Shahriyar 7
InetAddress
• Java has a class [Link] which abstracts
network addresses
• Major methods
– getLocalHost()
– getByAddress()
– getByName()
• Example: [Link], [Link], [Link]
Prepared By - Rifat Shahriyar 8
HttpURLConnection
• Java provides a class [Link]
that provides support for HTTP connections
• You can obtain HttpURLConnection by calling
openConnection( ) on URL object
• You must cast the result to HttpURLConnection
• You can then read/write from/to the connection
• Example: [Link]
Prepared By - Rifat Shahriyar 9
HttpClient
• Java 11 introduced a new networking package
[Link] (aka HTTP Client API)
– It provides enhanced networking support for HTTP clients
– Superior alternative to HttpURLConnection
• Classes: HttpClient, HttpRequest, HttpResponse
– Create an instance of HttpClient
– Construct an HttpRequest, send it by HttpClient’s send()
– The response is returned by send() from which the headers
and response body can be obtained
• Example: [Link]
Prepared By - Rifat Shahriyar 10