SlideShare una empresa de Scribd logo
1 de 39
Chapter 4
Network Programming
5/26/2023
Elements of Client -Server Computing
5/26/2023
Network
client, server, and network
Client
Server
Client machine
Server machine
Overview
5/26/2023
The term Network programming refers to writing programs that execute
across multiple devices (computers) in which the devices are all connected to
each other using a network.
Networking
• Java’s fundamental networking capabilities are declared by classes
and interfaces of the java.net package, through which Java
offers stream-based communications.
• The classes and interfaces of java.net also offer packet-based
communications for transmitting individual packets of information.
This is most commonly used to transmit audio and video over the
Internet.
• We will focus on both sides of the client-server relationship.
• The client requests that some action be performed, and the server
performs the action and responds to the client.
5/26/2023
Networking Classes in the JDK
• Through the classes in java.net Java programs can use TCP or UDP to
communicate over the Internet.
• For TCP communication:
 Socket
 ServerSocket
• For UDP communication:
 DatagramPacket
 DatagramSocket
 MulticastSocket
5/26/2023
TCP
• TCP (Transmission Control Protocol)
• A connection-oriented protocol.
• Allows reliable communication between two applications.
• Usually used over the Internet with IP as TCP/IP
• Resembles making a telephone call
• The person placing the telephone call – client
• The person waiting for a call – server
• The java.net.ServerSocket and java.net.Socket classes are the only two
classes you will probably ever need to create a TCP/IP connection between
two computers.
• For a secure connection, SSLServerSocket and SSLSocket classes in the
javax.net.ssl package are used.
5/26/2023
.. TCP
• Guarantees that data sent from one end of the connection actually gets
to the other end and in the same order it was sent. Otherwise, an error
is reported.
• The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and
Telnet are all examples of applications that require a reliable
communication channel.
5/26/2023
UDP
• UDP (User Datagram Protocol)
• A connectionless protocol.
• Allows packets of data (datagram) to be transmitted between applications.
• Resembles mailing someone a letter
• The datagram packet is like a letter, where a client sends a datagram to a server without
actually connecting to the server.
• This makes UDP an unreliable protocol
• UDP does not guarantee that packets will be received in the order they were sent
or that they will even be delivered at all.
• The java.net.DatagramPacket class –to send datagram packets
• The java.net.DatagramSocket class – to receive datagram packets
5/26/2023
…UDP
–Sender does not wait for acknowledgements
–Arrival order is not guaranteed
–Arrival is not guaranteed
• USED when speed is essential, even in cost of reliability
–e.g. streaming media, games, Internet telephony, etc.
5/26/2023
IP Address and Ports
• Data transmitted over the Internet is accompanied by addressing
information that identifies the computer and the port for which it
is destined.
– The computer is identified by its 32-bit IP address, which IP uses to
deliver data to the right computer on the network.
– Ports are identified by a 16-bit number, which TCP and UDP use to
deliver the data to the right application.
10
…Ports
• Port numbers range from 0 to 65,535 (16-bit)
• Ports 0 - 1024 are called well-known ports. They are
reserved for use by well-known services:
• 20, 21: FTP
• 23: TELNET
• 25: SMTP
• 110: POP3
• 80: HTTP
11
Internet Addresses
• Every computer on the Internet is identified by a unique, four-byte IP address.
 This is typically written in dotted quad format like 199.1.32.90 where each byte is an
unsigned value between 0 and 255.
• Java.net.InetAddress : Represents an IP address
(either IPv4 or IPv6) and has methods for performing DNS lookup.
• InetAddress getByName(String host) throws UnknownHostException
• InetAddress[] getAllByName(String host)throws UnknownHostException
• InetAddress getLocalHost() throws UnknownHostException
• boolean isMulticastAddress()
• String getHostName()
• byte[] getAddress()
• String getHostAddress()
• int hashCode()
• boolean equals(Object obj)
• String toString()
2/4/2013 Ch4: Network Programming Compiled by:Kidane W. 12
Sockets
• A program can read from a socket or write to a socket as simply as
reading from a file or writing to a file.
• A socket is simply a software construct that represents one
endpoint of a connection.
• Stream sockets enable a process to establish a connection with
another process. While the connection is in place, data flows
between the processes in continuous streams.
• Stream sockets provide a connection-oriented service. The
protocol used for transmission is the popular TCP (Transmission
Control Protocol). Provides reliable , in-order byte-stream service
5/26/2023
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
5/26/2023
Socket Communication
• A server (program) runs on a specific computer and has a socket that
is bound to a specific port.
• The server waits and listens to the socket for a client to make a
connection request.
5/26/2023
server
Client
Connection request
port
Socket Communication
• If everything goes well, the server accepts the connection.
• Upon acceptance, the server gets a new socket bounds to a different port. It
needs a new socket (consequently a different port number) so that it can
continue to listen to the original socket for connection requests while serving the
connected client.
5/26/2023
server
Client
Connection
port
port
port
Java Sockets
5/26/2023
ServerSocket(1234)
Socket(“128.250.25.158”, 1234)
Output/write stream
Input/read stream
It can be host_name like “intranet.amu.edu.et”
Client
Server
Socket
• There are four fundamental operations a socket performs. These are:
 Connect to a remote machine
 Send data
 Receive data
 Close the connection
• The java.net.Socket class allows you to perform all four
fundamental socket operations
• Connection is accomplished through the constructors.
• Each Socket object is associated with exactly one remote host. To
connect to a different host, you must create a new Socket object.
5/26/2023
Socket constructors
Socket(String host, int port) throws UnknownHostException, IOException
Socket(InetAddress address, int port) throws IOException
Socket(String host, int port, InetAddress localAddress, int localPort) throws
IOException
Socket(InetAddress address, int port, InetAddress localAddress, int localPort)
throws IOException
• Sending and receiving data is accomplished with output and input
streams.
 InputStream getInputStream() throws IOException
 OutputStream getOutputStream() throws IOException
• There's a method to close a socket.
 void close() throws IOException
5/26/2023
Socket methods
• There are methods to return information about the socket:
 InetAddress getInetAddress()
 InetAddress getLocalAddress()
 int getPort()
 int getLocalPort()
• Finally there's the usual toString() method:
 String toString()
5/26/2023
Constructing Socket Objects
• You need to at least specify the remote host and port you want to connect to.
Socket webSunsite = new Socket("metalab.unc.edu", 80);
Socket metalab = new Socket("metalab.unc.edu", 80, "calzone.oit.unc.edu",
0);
• The later constructors also specify the host and port you're connecting from.
• On a system with multiple IP addresses, like many web servers, this allows you to pick your network
interface and IP address.
• you should probably set the port number to 0 instead to tells the system to randomly choose an
available port.
• The Socket() constructors create a Socket object & attempt to connect the underlying socket to
the remote server.
5/26/2023
Socket Programming with TCP
• Server process must first be running (must have created
a socket). Recall that TCP is not connectionless.
• Client contacts the server by creating client-local socket
specifying IP address and port number of server process.
Client TCP establishes connection to server TCP.
• When contacted by client, server TCP creates a new
socket for server process to communicate with client.
• Allows server to talk with multiple clients
• Source port numbers used to distinguish clients
• From application viewpoint: TCP provides reliable, in-
order transfer of bytes (“pipe”) between client and
server.
5/26/2023
Establishing a Simple Server Using Stream Sockets
Five steps to create a simple stream server in Java:
1. ServerSocket object. Registers an available port and a
maximum number of clients.
2. Each client connection handled with a Socket object. Server
blocks until client connects.
3. Sending and receiving data
• OutputStream to send and InputStream to receive
data.
• Methods getInputStream and getOutputStream on
Socket object.
4. Process phase. Server and client communicate via streams.
5. Close streams and connections.
5/26/2023
Establishing a Simple Client Using Stream Sockets
Four steps to create a simple stream client in Java:
1. Create a Socket object for the client.
2. Obtains Socket’s InputStream and OutputStream.
3. Process information communicated.
4. Close streams and Socket.
5/26/2023
Sockets
int port=2000;
BufferedReader br;
PrintWriter pw;
ServerSocket ss;
Socket sock;
ss = new ServerSocket(port);
sock = ss.accept();
br = new BufferedReader(
new InputStreamReader(
(sock.getInputStream());
pw = new PrintWriter(
sock.getOutputStream());
System.out.println(
br.readLine());
pw.println("HELLO");
int port=2000;
String host=”cubist";
BufferedReader br;
PrintWriter pw;
Socket sock;
sock = new Socket(host,port);
br = new BufferedReader(
new InputStreamReader(
(sock.getInputStream());
pw = new PrintWriter(
sock.getOutputStream());
pw.println("ciao");
System.out.println(
br.readLine());
Server Client
Example: Java server using TCP
5/26/2023
//simple server application using TCP
import java.io.*;
import java.net.*;
class TCPServer {
public static void main (String args[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
//create welcoming socket at port 6789
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
//block on welcoming socket for contact by a client
Socket connectionSocket = welcomeSocket.accept();
//create input stream attached to socket
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader
(connectionSocket.getInputStream()));
Example: Java server using TCP (cont.)
5/26/2023
//create output stream attached to socket
DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());
//read in line from the socket
clientSentence = inFromClient.readLine();
//process
capitalizedSentence = clientSentence.toUpperCase() + 'n';
//write out line to socket
outToClient.writeBytes(capitalizedSentence);
}
}
}
Example: Java client using TCP
5/26/2023
//simple client application using TCP
import java.io.*;
import java.net.*;
class TCPClient {
public static void main (String args[]) throws Exception
{
String sentence;
String modifiedSentence;
//create input stream
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
//create client socket and connect to server
Socket clientSocket = new Socket("localhost", 6789);
//create output stream attached to socket
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
Example: Java client using TCP (cont.)
5/26/2023
//create input stream attached to socket
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader (clientSocket.getInputStream()));
sentence = inFromUser.readLine();
//send line to server
outToServer.writeBytes(sentence + 'n');
//read line from server
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
Start TCP Server
executing
Start a TCP Client
executing and send
message to server.
Server responds and client
process terminates. The
server is still executing.
Another client begins
execution and the cycle
repeats.
5/26/2023
Socket programming with UDP
• Datagram sockets transmit individual packets of information. This is
typically not appropriate for use by everyday programmers because the
transmission protocol is UDP (User Datagram Protocol).
• UDP provides a connectionless service. A connectionless service does
not guarantee that packets arrive at the destination in any particular
order.
• With UDP, packets can be lost or duplicated. Significant extra
programming is required on the programmer’s part to deal with these
problems.
• UDP is most appropriate for network applications that do not require
the error checking and reliability of TCP.
5/26/2023
…UDP
• Under UDP there is no “connection” between the server and the client.
There is no “handshaking”.
• The sender explicitly attaches the IP address and port of the destination
to each packet.
• The server must extract the IP address and port of the sender from the
received packet.
• From an application viewpoint, UDP provides unreliable transfer of groups
of bytes (“datagrams”) between client and server.
5/26/2023
…UDP
1. Create an array of bytes large enough to hold the data of the incoming
packet.
2. A DatagramPacket object is instantiated using the array of bytes.
3. A DatagramSocket is instantiated, and it is specified which port (and
specific localhost address, if necessary) on the localhost the socket will
bind to.
4. The receive() method of the DatagramSocket class is invoked, passing in
the DatagramPacket object. This causes the thread to block until a
datagram packet is received or a time out occurs.
5/26/2023
Steps to Receive a Datagram packet - UDP
…UDP
1. Create an array of bytes large enough to hold the data of the packet to be
sent, and fill the array with the data.
2. Create a new DatagramPacket object that contains the array of bytes, as well
as the server name and port number of the recipient.
3. A DatagramSocket is instantiated, and it is specified which port (and specific
localhost address, if necessary) on the localhost the socket will bind to.
4. The send() method of the DatagramSocket class is invoked, passing in the
DatagramPacket object.
5/26/2023
Steps to Send a Datagram packet - UDP
Example: Java server using UDP
5/26/2023
import java.io.*;
import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception
{
//Create datagram socket on port 9876
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
while (true)
{
//create space for the received datagram
DatagramPacket receivePacket = new
DatagramPacket(receiveData,
receiveData.length);
//receive the datagram
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
…Example: Java server using UDP
5/26/2023
//get IP address and port number of sender
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence =
sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
//create datagram to send to client
DatagramPacket sendPacket = new
DatagramPacket(sendData, sendData.length, IPAddress, port);
//write out the datagram to the socket
serverSocket.send(sendPacket);
} //end while loop
}
}
Example: Java client using UDP
5/26/2023
import java.io.*;
import java.net.*;
class UDPClient {
public static void main(String args[]) throws Exception
{
//Create input stream
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
//Create client socket
DatagramSocket clientSocket = new DatagramSocket();
//Translate hostname to IP address using DNS
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
…Example: Java client using UDP
5/26/2023
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
Start UDP server
executing
Start UDP client
executing
Client sends a
message
(datagram) to the
server
Server responds by
returning the
datagram to the
client in all capital
letters
5/26/2023

Más contenido relacionado

Similar a 5_6278455688045789623.pptx

Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Javasuraj pandey
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat applicationPiyush Rawat
 
OOP Lecture 24-Network Programming-Part1.pptx
OOP Lecture 24-Network Programming-Part1.pptxOOP Lecture 24-Network Programming-Part1.pptx
OOP Lecture 24-Network Programming-Part1.pptxTanzila Kehkashan
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
chapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhjchapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhjAmitDeshai
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in JavaTushar B Kute
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptxRoshniSundrani
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagarNitish Nagar
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programmingGera Paulos
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAMaulik Borsaniya
 
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriya
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriyaIPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriya
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriyaVijiPriya Jeyamani
 
Lan chat system
Lan chat systemLan chat system
Lan chat systemWipro
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat applicationSamsil Arefin
 

Similar a 5_6278455688045789623.pptx (20)

java networking
 java networking java networking
java networking
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
OOP Lecture 24-Network Programming-Part1.pptx
OOP Lecture 24-Network Programming-Part1.pptxOOP Lecture 24-Network Programming-Part1.pptx
OOP Lecture 24-Network Programming-Part1.pptx
 
Sockets
SocketsSockets
Sockets
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
chapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhjchapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhj
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in Java
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptx
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programming
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
 
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriya
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriyaIPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriya
IPT Chapter 2 Web Services and Middleware - Dr. J. VijiPriya
 
Lan chat system
Lan chat systemLan chat system
Lan chat system
 
Java 1
Java 1Java 1
Java 1
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
 
Networking in python by Rj
Networking in python by RjNetworking in python by Rj
Networking in python by Rj
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 

Más de EliasPetros

ghgfjfhgdjfdhgdhgfdgfdhgdhgfdhgzeka.pptx
ghgfjfhgdjfdhgdhgfdgfdhgdhgfdhgzeka.pptxghgfjfhgdjfdhgdhgfdgfdhgdhgfdhgzeka.pptx
ghgfjfhgdjfdhgdhgfdgfdhgdhgfdhgzeka.pptxEliasPetros
 
L04 - Control Structuresjhgjhgjhgjhgfjgfjhgfjgf.pptx
L04 - Control Structuresjhgjhgjhgjhgfjgfjhgfjgf.pptxL04 - Control Structuresjhgjhgjhgjhgfjgfjhgfjgf.pptx
L04 - Control Structuresjhgjhgjhgjhgfjgfjhgfjgf.pptxEliasPetros
 
lkjhlkjhjhkjhlkjhkjhkjhkjhkjhkjhjhkjh.ppt
lkjhlkjhjhkjhlkjhkjhkjhkjhkjhkjhjhkjh.pptlkjhlkjhjhkjhlkjhkjhkjhkjhkjhkjhjhkjh.ppt
lkjhlkjhjhkjhlkjhkjhkjhkjhkjhkjhjhkjh.pptEliasPetros
 
ehhhhhhhhhhhhhhhhhhhhhhhhhjjjjjllaye.pptx
ehhhhhhhhhhhhhhhhhhhhhhhhhjjjjjllaye.pptxehhhhhhhhhhhhhhhhhhhhhhhhhjjjjjllaye.pptx
ehhhhhhhhhhhhhhhhhhhhhhhhhjjjjjllaye.pptxEliasPetros
 
Database Akjljljlkjlkjkljlkjldiministration.pptx
Database Akjljljlkjlkjkljlkjldiministration.pptxDatabase Akjljljlkjlkjkljlkjldiministration.pptx
Database Akjljljlkjlkjkljlkjldiministration.pptxEliasPetros
 
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxhjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxEliasPetros
 
hjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptx
hjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptxhjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptx
hjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptxEliasPetros
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxEliasPetros
 
chaptet 4 DC and CN.ppt
chaptet 4 DC and CN.pptchaptet 4 DC and CN.ppt
chaptet 4 DC and CN.pptEliasPetros
 
chapter 1 DC and CN-1.ppt
chapter 1 DC and CN-1.pptchapter 1 DC and CN-1.ppt
chapter 1 DC and CN-1.pptEliasPetros
 

Más de EliasPetros (12)

ghgfjfhgdjfdhgdhgfdgfdhgdhgfdhgzeka.pptx
ghgfjfhgdjfdhgdhgfdgfdhgdhgfdhgzeka.pptxghgfjfhgdjfdhgdhgfdgfdhgdhgfdhgzeka.pptx
ghgfjfhgdjfdhgdhgfdgfdhgdhgfdhgzeka.pptx
 
L04 - Control Structuresjhgjhgjhgjhgfjgfjhgfjgf.pptx
L04 - Control Structuresjhgjhgjhgjhgfjgfjhgfjgf.pptxL04 - Control Structuresjhgjhgjhgjhgfjgfjhgfjgf.pptx
L04 - Control Structuresjhgjhgjhgjhgfjgfjhgfjgf.pptx
 
lkjhlkjhjhkjhlkjhkjhkjhkjhkjhkjhjhkjh.ppt
lkjhlkjhjhkjhlkjhkjhkjhkjhkjhkjhjhkjh.pptlkjhlkjhjhkjhlkjhkjhkjhkjhkjhkjhjhkjh.ppt
lkjhlkjhjhkjhlkjhkjhkjhkjhkjhkjhjhkjh.ppt
 
ehhhhhhhhhhhhhhhhhhhhhhhhhjjjjjllaye.pptx
ehhhhhhhhhhhhhhhhhhhhhhhhhjjjjjllaye.pptxehhhhhhhhhhhhhhhhhhhhhhhhhjjjjjllaye.pptx
ehhhhhhhhhhhhhhhhhhhhhhhhhjjjjjllaye.pptx
 
Database Akjljljlkjlkjkljlkjldiministration.pptx
Database Akjljljlkjlkjkljlkjldiministration.pptxDatabase Akjljljlkjlkjkljlkjldiministration.pptx
Database Akjljljlkjlkjkljlkjldiministration.pptx
 
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxhjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
 
hjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptx
hjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptxhjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptx
hjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptx
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
Chapter 08.pptx
Chapter 08.pptxChapter 08.pptx
Chapter 08.pptx
 
chaptet 4 DC and CN.ppt
chaptet 4 DC and CN.pptchaptet 4 DC and CN.ppt
chaptet 4 DC and CN.ppt
 
chapter 1 DC and CN-1.ppt
chapter 1 DC and CN-1.pptchapter 1 DC and CN-1.ppt
chapter 1 DC and CN-1.ppt
 

Último

(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 

Último (20)

(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 

5_6278455688045789623.pptx

  • 2. Elements of Client -Server Computing 5/26/2023 Network client, server, and network Client Server Client machine Server machine
  • 3. Overview 5/26/2023 The term Network programming refers to writing programs that execute across multiple devices (computers) in which the devices are all connected to each other using a network.
  • 4. Networking • Java’s fundamental networking capabilities are declared by classes and interfaces of the java.net package, through which Java offers stream-based communications. • The classes and interfaces of java.net also offer packet-based communications for transmitting individual packets of information. This is most commonly used to transmit audio and video over the Internet. • We will focus on both sides of the client-server relationship. • The client requests that some action be performed, and the server performs the action and responds to the client. 5/26/2023
  • 5. Networking Classes in the JDK • Through the classes in java.net Java programs can use TCP or UDP to communicate over the Internet. • For TCP communication:  Socket  ServerSocket • For UDP communication:  DatagramPacket  DatagramSocket  MulticastSocket 5/26/2023
  • 6. TCP • TCP (Transmission Control Protocol) • A connection-oriented protocol. • Allows reliable communication between two applications. • Usually used over the Internet with IP as TCP/IP • Resembles making a telephone call • The person placing the telephone call – client • The person waiting for a call – server • The java.net.ServerSocket and java.net.Socket classes are the only two classes you will probably ever need to create a TCP/IP connection between two computers. • For a secure connection, SSLServerSocket and SSLSocket classes in the javax.net.ssl package are used. 5/26/2023
  • 7. .. TCP • Guarantees that data sent from one end of the connection actually gets to the other end and in the same order it was sent. Otherwise, an error is reported. • The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require a reliable communication channel. 5/26/2023
  • 8. UDP • UDP (User Datagram Protocol) • A connectionless protocol. • Allows packets of data (datagram) to be transmitted between applications. • Resembles mailing someone a letter • The datagram packet is like a letter, where a client sends a datagram to a server without actually connecting to the server. • This makes UDP an unreliable protocol • UDP does not guarantee that packets will be received in the order they were sent or that they will even be delivered at all. • The java.net.DatagramPacket class –to send datagram packets • The java.net.DatagramSocket class – to receive datagram packets 5/26/2023
  • 9. …UDP –Sender does not wait for acknowledgements –Arrival order is not guaranteed –Arrival is not guaranteed • USED when speed is essential, even in cost of reliability –e.g. streaming media, games, Internet telephony, etc. 5/26/2023
  • 10. IP Address and Ports • Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined. – The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network. – Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right application. 10
  • 11. …Ports • Port numbers range from 0 to 65,535 (16-bit) • Ports 0 - 1024 are called well-known ports. They are reserved for use by well-known services: • 20, 21: FTP • 23: TELNET • 25: SMTP • 110: POP3 • 80: HTTP 11
  • 12. Internet Addresses • Every computer on the Internet is identified by a unique, four-byte IP address.  This is typically written in dotted quad format like 199.1.32.90 where each byte is an unsigned value between 0 and 255. • Java.net.InetAddress : Represents an IP address (either IPv4 or IPv6) and has methods for performing DNS lookup. • InetAddress getByName(String host) throws UnknownHostException • InetAddress[] getAllByName(String host)throws UnknownHostException • InetAddress getLocalHost() throws UnknownHostException • boolean isMulticastAddress() • String getHostName() • byte[] getAddress() • String getHostAddress() • int hashCode() • boolean equals(Object obj) • String toString() 2/4/2013 Ch4: Network Programming Compiled by:Kidane W. 12
  • 13. Sockets • A program can read from a socket or write to a socket as simply as reading from a file or writing to a file. • A socket is simply a software construct that represents one endpoint of a connection. • Stream sockets enable a process to establish a connection with another process. While the connection is in place, data flows between the processes in continuous streams. • Stream sockets provide a connection-oriented service. The protocol used for transmission is the popular TCP (Transmission Control Protocol). Provides reliable , in-order byte-stream service 5/26/2023
  • 14. 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 5/26/2023
  • 15. Socket Communication • A server (program) runs on a specific computer and has a socket that is bound to a specific port. • The server waits and listens to the socket for a client to make a connection request. 5/26/2023 server Client Connection request port
  • 16. Socket Communication • If everything goes well, the server accepts the connection. • Upon acceptance, the server gets a new socket bounds to a different port. It needs a new socket (consequently a different port number) so that it can continue to listen to the original socket for connection requests while serving the connected client. 5/26/2023 server Client Connection port port port
  • 17. Java Sockets 5/26/2023 ServerSocket(1234) Socket(“128.250.25.158”, 1234) Output/write stream Input/read stream It can be host_name like “intranet.amu.edu.et” Client Server
  • 18. Socket • There are four fundamental operations a socket performs. These are:  Connect to a remote machine  Send data  Receive data  Close the connection • The java.net.Socket class allows you to perform all four fundamental socket operations • Connection is accomplished through the constructors. • Each Socket object is associated with exactly one remote host. To connect to a different host, you must create a new Socket object. 5/26/2023
  • 19. Socket constructors Socket(String host, int port) throws UnknownHostException, IOException Socket(InetAddress address, int port) throws IOException Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException Socket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException • Sending and receiving data is accomplished with output and input streams.  InputStream getInputStream() throws IOException  OutputStream getOutputStream() throws IOException • There's a method to close a socket.  void close() throws IOException 5/26/2023
  • 20. Socket methods • There are methods to return information about the socket:  InetAddress getInetAddress()  InetAddress getLocalAddress()  int getPort()  int getLocalPort() • Finally there's the usual toString() method:  String toString() 5/26/2023
  • 21. Constructing Socket Objects • You need to at least specify the remote host and port you want to connect to. Socket webSunsite = new Socket("metalab.unc.edu", 80); Socket metalab = new Socket("metalab.unc.edu", 80, "calzone.oit.unc.edu", 0); • The later constructors also specify the host and port you're connecting from. • On a system with multiple IP addresses, like many web servers, this allows you to pick your network interface and IP address. • you should probably set the port number to 0 instead to tells the system to randomly choose an available port. • The Socket() constructors create a Socket object & attempt to connect the underlying socket to the remote server. 5/26/2023
  • 22. Socket Programming with TCP • Server process must first be running (must have created a socket). Recall that TCP is not connectionless. • Client contacts the server by creating client-local socket specifying IP address and port number of server process. Client TCP establishes connection to server TCP. • When contacted by client, server TCP creates a new socket for server process to communicate with client. • Allows server to talk with multiple clients • Source port numbers used to distinguish clients • From application viewpoint: TCP provides reliable, in- order transfer of bytes (“pipe”) between client and server. 5/26/2023
  • 23. Establishing a Simple Server Using Stream Sockets Five steps to create a simple stream server in Java: 1. ServerSocket object. Registers an available port and a maximum number of clients. 2. Each client connection handled with a Socket object. Server blocks until client connects. 3. Sending and receiving data • OutputStream to send and InputStream to receive data. • Methods getInputStream and getOutputStream on Socket object. 4. Process phase. Server and client communicate via streams. 5. Close streams and connections. 5/26/2023
  • 24. Establishing a Simple Client Using Stream Sockets Four steps to create a simple stream client in Java: 1. Create a Socket object for the client. 2. Obtains Socket’s InputStream and OutputStream. 3. Process information communicated. 4. Close streams and Socket. 5/26/2023
  • 25. Sockets int port=2000; BufferedReader br; PrintWriter pw; ServerSocket ss; Socket sock; ss = new ServerSocket(port); sock = ss.accept(); br = new BufferedReader( new InputStreamReader( (sock.getInputStream()); pw = new PrintWriter( sock.getOutputStream()); System.out.println( br.readLine()); pw.println("HELLO"); int port=2000; String host=”cubist"; BufferedReader br; PrintWriter pw; Socket sock; sock = new Socket(host,port); br = new BufferedReader( new InputStreamReader( (sock.getInputStream()); pw = new PrintWriter( sock.getOutputStream()); pw.println("ciao"); System.out.println( br.readLine()); Server Client
  • 26. Example: Java server using TCP 5/26/2023 //simple server application using TCP import java.io.*; import java.net.*; class TCPServer { public static void main (String args[]) throws Exception { String clientSentence; String capitalizedSentence; //create welcoming socket at port 6789 ServerSocket welcomeSocket = new ServerSocket(6789); while (true) { //block on welcoming socket for contact by a client Socket connectionSocket = welcomeSocket.accept(); //create input stream attached to socket BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connectionSocket.getInputStream()));
  • 27. Example: Java server using TCP (cont.) 5/26/2023 //create output stream attached to socket DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); //read in line from the socket clientSentence = inFromClient.readLine(); //process capitalizedSentence = clientSentence.toUpperCase() + 'n'; //write out line to socket outToClient.writeBytes(capitalizedSentence); } } }
  • 28. Example: Java client using TCP 5/26/2023 //simple client application using TCP import java.io.*; import java.net.*; class TCPClient { public static void main (String args[]) throws Exception { String sentence; String modifiedSentence; //create input stream BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); //create client socket and connect to server Socket clientSocket = new Socket("localhost", 6789); //create output stream attached to socket DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  • 29. Example: Java client using TCP (cont.) 5/26/2023 //create input stream attached to socket BufferedReader inFromServer = new BufferedReader(new InputStreamReader (clientSocket.getInputStream())); sentence = inFromUser.readLine(); //send line to server outToServer.writeBytes(sentence + 'n'); //read line from server modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } }
  • 30. Start TCP Server executing Start a TCP Client executing and send message to server. Server responds and client process terminates. The server is still executing. Another client begins execution and the cycle repeats. 5/26/2023
  • 31. Socket programming with UDP • Datagram sockets transmit individual packets of information. This is typically not appropriate for use by everyday programmers because the transmission protocol is UDP (User Datagram Protocol). • UDP provides a connectionless service. A connectionless service does not guarantee that packets arrive at the destination in any particular order. • With UDP, packets can be lost or duplicated. Significant extra programming is required on the programmer’s part to deal with these problems. • UDP is most appropriate for network applications that do not require the error checking and reliability of TCP. 5/26/2023
  • 32. …UDP • Under UDP there is no “connection” between the server and the client. There is no “handshaking”. • The sender explicitly attaches the IP address and port of the destination to each packet. • The server must extract the IP address and port of the sender from the received packet. • From an application viewpoint, UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server. 5/26/2023
  • 33. …UDP 1. Create an array of bytes large enough to hold the data of the incoming packet. 2. A DatagramPacket object is instantiated using the array of bytes. 3. A DatagramSocket is instantiated, and it is specified which port (and specific localhost address, if necessary) on the localhost the socket will bind to. 4. The receive() method of the DatagramSocket class is invoked, passing in the DatagramPacket object. This causes the thread to block until a datagram packet is received or a time out occurs. 5/26/2023 Steps to Receive a Datagram packet - UDP
  • 34. …UDP 1. Create an array of bytes large enough to hold the data of the packet to be sent, and fill the array with the data. 2. Create a new DatagramPacket object that contains the array of bytes, as well as the server name and port number of the recipient. 3. A DatagramSocket is instantiated, and it is specified which port (and specific localhost address, if necessary) on the localhost the socket will bind to. 4. The send() method of the DatagramSocket class is invoked, passing in the DatagramPacket object. 5/26/2023 Steps to Send a Datagram packet - UDP
  • 35. Example: Java server using UDP 5/26/2023 import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { //Create datagram socket on port 9876 DatagramSocket serverSocket = new DatagramSocket(9876); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; while (true) { //create space for the received datagram DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); //receive the datagram serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData());
  • 36. …Example: Java server using UDP 5/26/2023 //get IP address and port number of sender InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); //create datagram to send to client DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); //write out the datagram to the socket serverSocket.send(sendPacket); } //end while loop } }
  • 37. Example: Java client using UDP 5/26/2023 import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { //Create input stream BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); //Create client socket DatagramSocket clientSocket = new DatagramSocket(); //Translate hostname to IP address using DNS InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes();
  • 38. …Example: Java client using UDP 5/26/2023 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } }
  • 39. Start UDP server executing Start UDP client executing Client sends a message (datagram) to the server Server responds by returning the datagram to the client in all capital letters 5/26/2023