Chuong5 Networking Updated

Download as pdf or txt
Download as pdf or txt
You are on page 1of 77

1

➢ Networking Basics
➢ Working with URL
➢ Socket
➢ Remote Method Invocation

2
➢ Some definitions related to networking
➢ Client-Server Model

3
➢ Platform: hardware + operating system.
➢ Client: an application running in a computer (such as browser)
can receive data from another (server).
➢ Server: an application running in a computer (such as IIS-
Windows Internet Information Service) can supply data to
others (clients).
➢ IP address (internet protocol): unsigned integer helps
identifying a network element(computer, router,…).
➢ IPv4: 4-byte IP address, such as 192.143.5.1
➢ IPv6: 16-byte IP address
➢ Port: unsigned 2-byte integer helps operating system
differentiating a network communicating process.
➢ Protocol: Rules for packaging data of a network communication
because client and server can be working in different platform.
Two common basic protocols are TCP and UDP 4
➢ TCP: (Transmission Control Protocol) is a connection-based
protocol (only one connecting line only) that provides a
reliable flow of data between two computers based on the
acknowledge mechanism.
➢ UDP: (User Datagram Protocol) is a protocol that sends
independent packets of data, called datagrams, from one
computer to another with no guarantees about arrival (many
connecting lines can be used, acknowledge mechanism is not
used). Many firewalls and routers have been configured not
to allow UDP packets. Ask your system administrator if UDP
is permitted.
➢ Serialization: a process that converts object’s state (values
in fields of the object) to a byte stream.
➢ De- serialization: a process that splits data in a byte stream
then set data to fields of an object. 5
Step 2: Server
Step 1: Client analyzes the
sends a request then
request to process it
server Request can be
(file.html, file.txt
Script file -.asp, .aspx. .php, .jsp….
Execute a method of running object

Response:
File.html, .txt,…
Server
Client Result of processing
( can be a container,
(can be a browser) web container or
Step 3: Server Application container)
sends
response to
client
6
➢ Computers running on the Internet communicate
to each other:

data data

Port H1 data H1 data

IP H2 H1 data H2 H1 data

H3 H2 H1 data H3 H2 H1 data
Network
Environment

A package is attached an appropriate header (H-identifiable data) when it is


transferred to each layer. A layer is an applications or a function library of
network managing system

7
➢ How to distinguish a computer in a network?

IP:152.3.21.121 or Hostname
Personal computer IP: 127.0.0.1
An IP address is either a 32-bit or 128-bit
unsigned number used by IP, a lower-level
protocol on which protocols like UDP and
TCP are built. The IP address architecture
is defined by RFC 790:

8
How to distinguish a network-communicating process in a computer?
PORT

9
How to specify a resource in internet/network?

URL: Uniform Resource Locator


URN: Uniform Resource Name. It involves URL and pathname

http://www.abc.com:80/users/index.html

Port
Protocol :// Host : File
(option)

Object name

"rmi://localhost:1098/Math1";
10
➢ The package java.net
➢ The class java.net.URL
➢ Demonstrations for using the URL and
URLConnection classes to get contents from
urls.

11
➢ It contains basic APIs for connecting computer networks.
➢ Reference: docs-Java8/api/java/net/package-tree.html
➢ Common used classes:
– java.net.URL (implements java.io.Serializable)
– java.net.URLConnection ( abstract class)
• java.net.HttpURLConnection
• java.net.JarURLConnection
– java.net.URLDecoder
– java.net.URLEncoder
– java.net.URLStreamHandler
– java.net.ServerSocket (implements java.io.Closeable)
– java.net.Socket (implements java.io.Closeable)
➢ This session will introduce the URL only.
12
➢ A URL takes the form of a string that describes how to find a
resource on the Internet. URLs have two main components: the
protocol needed to access the resource and the location of the
resource.
➢ public final class URL extends Object implements Serializable
➢ Constructors:
URL(String spec) Creates a URL object from
the String representation.
URL(String protocol, String host, int port, String file) Creates
a URL object from the specified protocol, host, port number,
and file.
URL(String protocol, String host, String file) Creates a URL
from the specified protocol name, host name, and file name.

13
➢ This program will get
components in a URL
and no connection is
carried out. 14
In the following program, if user enters a URL then clicks the button
Connect, the content of this URL will be shown. If inputted URL string is
malformed, a message will be shown.

15
16
17
Use the function REFRACTOR of NetBeans to
copy and rename the class ReadURL to
ReadURLConnection, modify code to gain the
similar result as following:

18
19
This code is modified
from those in the
previous demo.

This code is not


different from those in
the previous demo.
20
➢ A socket is one 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 is destined
to be sent.
➢ Main members:
Socket = IP + Port + IO Streams + Methods

21
➢ The java.net.Socket class implements one side
of a two-way connection between your Java
program and another program on the network
➢ The java.net.ServerSocket implements server
sockets. A server socket waits for requests to
come in over the network. It performs some
operation based on that request, and then
possibly returns a result to the requester.

22
Server:Mangalo Client: Jane
(1) Init
(Jane, xxxx)
(1) Make connection
srvSocket(1234)
(2) Accept (2) Receive the ACK from server
(3) Create socket (3) Create socket ACKnowledge

socket(Jane,xxxx) socket(Mangalo,1234)
outputStream outputStream
010010011001100 101100100110010
Input stream Input stream
101100100110010 automatically 010010011001100

(3) Loop (3) Loop


Process data in input stream. Process data in input stream.
Write data to output stream. Write data to output stream.

23
Server
Program
Name: Client
mangfalo Program
or IP

ServerSocket ss= new Socket srvSocket= new


ServerSocket(1234); Socket(“mangfalo”,1234);
Socket clientSoctket=ss.accept();
// Receive data
bf= new BufferedReader( new InputStreamReader(socket.getInputStream()));
aString= bf.readLine();
// Send data
os= new DataOutputStream (socket.getOutputStream());
os.writeBytes( aString); os.write(13); os.write(10); os.flush();
24
➢ B1: Khởi tạo đối tượng ServerSocket để lắng nghe
yêu cầu kết nối từ Client.
Sử dụng một vòng lặp để thực hiện các bước từ B2
đến B5:
➢ B2: Gọi phương thức accept() để chấp nhận.
Phương thức này trả về một đối tượng Socket để
trao đổi dữ liệu với client.
➢ B3: Sử dụng phương thức getInputStream() và
getOutputStream() lấy các luồng vào-ra để trao đổi
dữ liệu với client.
➢ B4: Trao đổi dữ liệu với client.
➢ B5: Đóng Socket kết nối với client.
➢ B6: Đóng ServerSocket.
25
26
27
➢ B1: Khởi tạo đối tượng Socket để kết nối đến
Server.
➢ B2: Sử dụng phương thức getInputStream() và
getOutputStream() lấy các luồng vào-ra để trao
đổi dữ liệu với server.
– Gửi-nhận dữ liệu với Socket giống vào-ra trên file.
– Cần sử dụng linh hoạt các loại luồng vào-ra trong
Java.
➢ B4: Trao đổi dữ liệu với server.
➢ B5: Đóng Socket.
28
29
30
➢ Sử dụng luồng ObjectOutputStream để gửi
đối tượng qua Socket
– Phương thức Object writeObject(Object o)
➢ Sử dụng luồng ObjectInputStream để nhận
đối tượng từ socket
– Phương thức Object readObject()
➢ Đối tượng truyền trên socket phải thuộc lớp
được thực thi từ interface Serializable.

31
32
33
34
35
36
➢ Với các ví dụ trên, một server tại một thời
điểm chỉ xử lý một client
→ Không thể đáp ứng nhiều yêu cầu cùng
một lúc.
➢ Sử dụng đa luồng (multithread) để khắc phục
nhược điểm trên
– Khi có một client kết nối đến server (accept)
– Tạo ra một luồng để xử lý công việc với client
đó.
37
38
39
Problem
➢ A manager wants to communicate with his/her staffs.
Each communication is distinct from others.
➢ Write Java programs which allow this manager and
his/her staffs carrying out their communications.
➔Each client program is used by a staff.
➔The program used by the manager has some
threads, each thread supports a communication
between the manager and a staff.
➔Manager site is specified by IP and the port 12340.
40
2 staffs and manager – when no connection is established

41
2 staffs and manager – when 2 connections is established

42
ChatPanel: Panel for chatting, it is used in
client and server.
ClientChatter: GUI client program for staffs
ManagerChatter: GUI Server program for
manager
OutputThread: a thread helps presenting
received data ( 1 time/second)

43
44
45
46
47
48
49
50
51
52
53
The Java Remote Method
Invocation (Java RMI) is
a Java API that performs the
object-oriented equivalent
of remote procedure
calls (RPC), with support for
direct transfer of serialized
Java classes and distributed
garbage collection.
The original implementation
depends on JVM class
representation mechanisms
and it thus only supports
making calls from one JVM
to another. The protocol
underlying this Java-only
It is the basic for protocols used in Java
implementation is known
application server, JBoss for example.
as Java Remote Method 54
Server object

bind

Client object
respon RMI Container
Lookup server object se Server database
Network [ Name1, serverObject1]
Server_Stub Environment [ Name2, serverObject2]

reques
t
Client JVM
Server JVM

In Windows, RMI container, pre-


defined in JDK, is the program We can create a RMI
rmiregistry.exe container by an Java
55
object. See demo.
Remote Remote
interface Client Server interface

Object Object The Stub, Skeleton


A B is omitted from Java
1.6
Object B Object B R
Stub Skeleton E
M
O
T
E

R
E
Remote Reference Layer Remote Reference Layer G
I
S
T
R
Transport Layer Transport Layer Y

From Java 1.6, code for network communicating is implemented automatically


56
1. Create the remote interface
2. Create the remote class (server)
implementing the remote interface.
3. Create Server program using server object
4. Create the client program
5. Run apps: Start server program first then
the client program.

57
The Stub,
Skeleton is
omitted
from Java
1.6

Step 1: Create a
remote interface

58
Step 2: Create server class implementing
remote interface

59
Step 3: Create server program in which a
server object is used

URN: Uniform Resource Name

60
Step 4: Create client program in
which the remote interface is
used

61
Call methods of remote object

62
Step 6: Run server program first then client program

63
In server program Disadvantages
- Platform
dependent
- An exception is
thrown when we
run the server
program again
because
rmiregistry.exe
must be
terminated after
each run ( use
task manager/
Processes)

64
In server program
// Using default RMI container in JVM
import java.rmi.registry.LocateRegistry;

String serviceName =
"rmi://localhost:1098/Math1";

LocateRegistry.createRegistry(1098);

65
In client program

String serviceName=
"rmi://localhost:1098/Math1";

66
➢ At server side
– An initial list of employees is stored in the
employees.txt file ( a line for an employee
with the format: code, Name, salary).
– A program running in console mode in which
a remote server can support two operations:
• Supply initial list of employees to a client program.
• Save using override mode a list of employees
transferred from a client program.
67
➢ At client side:
– Initially, a list of employees
is supplied from server will
be presented on a table of
the GUI.
– User can
• Add new employee ( the
employee’s code must have
the format E000 and it is not
duplicated with existing
employee codes.
• Remove an employee.
• Update employee details.
• Save the list on server.

68
69
70
71
// Using default RMI container in JVM
import java.rmi.registry.LocateRegistry;

String serviceName =
"rmi://localhost:1098/EmployeeService”

LocateRegistry.createRegistry(1098);

72
➢ Client Program

73
String serviceName =
"rmi://localhost:1098/EmployeeServic
e”

74
75
76
Step 1- Run server program Step 2- Run client program

77

You might also like