Professional Documents
Culture Documents
Chapter 2
Chapter 2
Chapter 2
Ref: Dr. Rajkumar Buyya, R. Buyya, S. Selvi, X. Chu, “Object Oriented Programming with Java: Essentials1and Applications
McGraw Hill, New Delhi, India, 2009
AGENDA
• Introduction
• Networking Basics
• Understanding Ports and Sockets
• Java Sockets
• Implementing a Server
• Implementing a Client
• Sample Examples
• Conclusions
2
INTRODUCTION
3
INTERNET APPLICATIONS SERVING LOCAL AND
REMOTE USERS
PC client
Internet
Server
Local Area Network
PDA
4
INCREASING DEMAND FOR
INTERNET APPLICATIONS
5
ELEMENTS OF CLIENT SERVER
COMPUTING
a client, a server, and network
network
client
server
◼ Processes follow protocols that define a set of rules that must be observed by participants:
◼ How the data exchange is encoded?
◼ How events (sending, receiving) are synchronized (ordered) so that participants can send and receive data in a coordinated manner?
◼ In face-to-face communication, humans beings follow unspoken protocols based on eye contact, body language, gesture.
6
NETWORKING BASICS
Physical/Link Layer
•
• Functionalities for transmission of signals representing a stream of
• TCP/IP Stack
Application
data from one computer to another
• Internet/Network Layer
(http,ftp,telnet,…)
• IP (Internet Protocols) – a packet of data to be addressed to a remote
computer and delivered Transport
• Transport Layer
• Functionalities for delivering data packets to a specific process on a
(TCP, UDP,..)
remote computer
• TCP (Transmission Control Protocol) Internet/Network
• UDP (User Datagram Protocol)
• Programming Interface:
(IP,..)
• Sockets
• Applications Layer Physical/Link
• Message exchange between standard or user applications: (device driver,..)
• HTTP, FTP, Telnet
7
NETWORKING BASICS
8
NETWORKING BASICS
9
TCP VS UDP COMMUNICATION
A … B
Connection-Oriented Communication
A
… B
Connectionless Communication
10
UNDERSTANDING PORTS
P
o TCP
server
r Client
• The TCP and UDP protocols use ports to t
map incoming data to a particular process
running on a computer.
12
SOCKETS
13
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.
Connection request
port
server Client
14
SOCKET COMMUNICATION
server
port
Client
port Connection
15
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
16
Server JAVA SOCKETS
ServerSocket(1234)
Input/read stream
Socket(“128.250.25.158”, 1234)
17
It can be host_name like “mandroo.cs.mu.oz.au”
IMPLEMENTING A SERVER
1. Open the Server Socket:
val server = new ServerSocket( PORT )
2. Wait for the Client Request:
val client: Socket = server.accept()
3. Create I/O streams for communicating to the client
val is = new DataInputStream( client.getInputStream() )
val os = new DataOutputStream( client.getOutputStream() )
4. Perform communication with client
Receive from client: var line: String = is.readLine()
Send to client: os.writeBytes("Hello\n")
5. Close sockets: client.close()
For multithreaded server:
while(true) {
i. wait for client requests (step 2 above)
ii. create a thread with “client” socket as parameter (the thread creates streams (as in step
(3) and does communication as stated in (4). Remove thread once service is provided.
}
18
IMPLEMENTING A CLIENT
19
A SIMPLE SERVER (SIMPLIFIED CODE)
• import java.io.{DataInputStream, DataOutputStream}
import java.net.ServerSocket
try {
// Get a communication stream associated with the socket
val is = new DataInputStream(client.getInputStream())
// Get a communication stream associated with the socket
val os = new DataOutputStream(client.getOutputStream())
// Read from input stream
var line: String = is.readLine()
// sending string
os.writeBytes("hello from server\n")
println(line)
} catch {
case e: Exception => e.printStackTrace
} finally {
// Close the connection, but not the server socket
client.close()
} 20
}
A SIMPLE CLIENT (SIMPLIFIED CODE)
22
SOCKET EXCEPTIONS
try {
val client: Socket = new Socket(host, port); handleConnection(client);
}
catch {
case uhe: UnknownHostException =>
println("Unknown host: " + host); uhe.printStackTrace()
case ioe: IOException =>
println("IOException: " + ioe); ioe.printStackTrace();
}
23
SERVERSOCKET & EXCEPTIONS
24
SERVER IN LOOP: ALWAYS UP
• import java.io.{DataInputStream, DataOutputStream}
import java.net.ServerSocket
try {
// Get a communication stream associated with the socket
val is = new DataInputStream(client.getInputStream())
// Get a communication stream associated with the socket
val os = new DataOutputStream(client.getOutputStream())
// Read from input stream
var line: String = is.readLine()
// sending string
os.writeBytes("hello from server\n")
println(line)
} catch {
case e: Exception => e.printStackTrace
} finally {
// Close the connection, but not the server socket
client.close()
}
}
}
25
MULTITHREAD SERVER
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
object server extends App {
// Register service on port 9000
val server = new ServerSocket(9000)
while(true) {
// Register service on port 1234
val socket = server.accept()
Future {
//store local socket references for processing
val client = socket
try {
// Get a communication stream associated with the socket
val is = new DataInputStream(client.getInputStream())
// Get a communication stream associated with the socket
val os = new DataOutputStream(client.getOutputStream())
// Read from input stream
var line: String = is.readLine()
// sending string
os.writeBytes("hello from server\n")
println(line)
} catch {
case e: Exception => e.printStackTrace
} finally {
// Close the connection, but not the server socket
client.close()
}
}
}
}
JAVA API FOR UDP PROGRAMMING
• DatagramSocket
27
UDP CLIENT: SENDS A MESSAGE
AND GETS REPLY
• import java.net._
import java.io._
object UDPClient extends App {
var aSocket: Option[DatagramSocket] = None
try {
aSocket = Some(new DatagramSocket())
val m: Array[Byte] = "how are you".getBytes
val aHost: InetAddress = InetAddress.getByName("localhost")
val serverPort: Int = 6789
val request: DatagramPacket = new DatagramPacket(m, m.length, aHost,
serverPort)
aSocket.get.send(request)
val buffer: Array[Byte] = Array.ofDim(1000)
val reply: DatagramPacket = new DatagramPacket(buffer, buffer.length)
aSocket.get.receive(reply)
println("Reply: " + new String(reply.getData()).trim)
} catch {
case e: SocketException => println("Socket: " + e.getMessage());
case e: IOException => println("IO: " + e.getMessage());
} finally {
aSocket foreach (_.close())
} 28
}
UDP SEVER: REPEATEDLY
RECEIVED A REQUEST AND
SENDS IT BACK TO THE CLIENT
• import java.net._
import java.io._
object UDPServer extends App {
var aSocket: Option[DatagramSocket] = None
try {
aSocket = Some(new DatagramSocket(6789))
val buffer: Array[Byte] = Array.ofDim[Byte](1000)
while (true) {
val request: DatagramPacket = new DatagramPacket(buffer,
buffer.length)
aSocket.get.receive(request)
val reply: DatagramPacket = new DatagramPacket(request.getData(),
request.getLength(), request.getAddress(), request.getPort())
aSocket.get.send(reply)
}
} catch {
case e: SocketException => println("Socket: " + e.getMessage())
case e: IOException => println("IO: " + e.getMessage())
} finally {
aSocket foreach (_.close())
}
}
29
MULTITHREADED SERVER: FOR
SERVING MULTIPLE CLIENTS
CONCURRENTLY
Server Process
Client Process 2
Server threads
Client Process 1 30
SUMMARY
31
REFERENCES
32