Download presentation
Presentation is loading. Please wait.
1
Socket-based Client-Server Application
Client-Server application architecture Choosing services – Connectionless atau Connection-oriented
2
Evolution of Application Architecture
3
3-tier Client-server application architecture
4
Internet Protocol and Network Application
Internet protocol supports: General-purpose service for reliable data transmission Mechanism for connecting hosts Network application programs: Use Internet Protocol to connect to other application Provide user-level services
5
Client-Server Model Server Application acts as a “listener”
Waits for incoming messages Executes services Returns the results/outcomes Client Application makes connection Sends messages to the server Waits for response
6
Features of a Client An application program
Becomes a client when a network service is needed It can also executes other calculation Is directly created by the users Is executed locally by at the users’ computer Initiates connection to a server Able to access various services (at a given time) Does not require a special device or operating system
7
Features of a Server Special-purpose application for providing a network service Is executed on a remote computer (usually is centralised and shared) Waits and receives request for services from the clients Requires high-performance device and operating system
8
Transport Protocol and Client-Server
Client and server exchange messages via transport protocol such as TCP or UDP Both client and server must have the same protocol stack and both interact with the transport layer
9
Transport Protocol and Client-Server
10
Several Services on a Server
11
Identifying a Service Every service has a unique identifier which is used by the client and server Example - TCP uses port number protocol (port_num) as identifier Server is registered under a specific port number for a service Client asks for a session with the port number for the service Every transport session contains 2 unique indentifier (IP address, port number) at the server (IP address, port number) at the client
12
Connection-oriented and Connectionless Transport Protocol
Which one should be chosen? UDP - connectionless Client builds a message Client sends the message to a server The server responds Message must be loaded into a UDP datagram TCP - connection-oriented Client makes a connection to a server Client and server exchange messages Client terminates the connection
13
UDP UDP is a connectionless transport protocol, i.e. it doesn't guarantee either packet delivery or that packets arrive in sequential order. With UDP, bytes of data are grouped together in discrete packets which are sent over the network.
14
No two packets are guaranteed the same route.
Packets may travel along different paths depending on the state of the network. No two packets are guaranteed the same route. Each packet has a time-to-live (TTL) counter, which is updated when it is routed along to the next point in the network. When the timer expires, it will be discarded, and the recipient will not be notified.
15
If a packet does arrive, it will always arrive intact
If a packet does arrive, it will always arrive intact. Packets that are corrupt or only partially delivered are discarded.
16
Advantages of UDP UDP communication can be more efficient than guaranteed-delivery data streams. Unlike TCP streams, which establish a connection, UDP causes fewer overheads. Real-time applications that demand up-to-the-second or better performance may be candidates for UDP, as there are fewer delays due to error checking and flow control of TCP.
17
UDP sockets can receive data from more than one host machine.
Some network protocols specify UDP as the transport mechanism.
18
Java Support for UDP Two classes are provided:
DatagramPacket class (java.net) DatagramSocket class (java.net)
19
DatagramPacket Class A DatagramPacket object represents a data packet intended for transmission using UDP. It contains addressing information such as an IP address and a port. When a DatagramPacket is read from a UDP socket, the IP address/port number of the packet represents the address/port number of the sender.
20
When a DatagramPacket is used to send a UDP packet, the IP address/port represents the address/port of the recipient. DatagramPacket IP address (java.net.InetAddr) Port address (int) Packet data (byte[])
21
Creating a DatagramPacket
Constructor to use for creating a DatagramPacket for receiving incoming UDP packets: DatagramPacket(byte[] buffer, int length) Example: DatagramPacket packet; packet = new DatagramPacket(new byte[256], 256);
22
Constructor to use for sending a DatagramPacket to a remote machine
DatagramPacket(byte[] buffer, int length, InetAddress dest_addr, int dest_port) Example: DatagramPacket packet; InetAddress addr; addr = InetAddress.getByName(" "); packet = new DatagramPacket(new byte[128], ,addr, 2000);
23
DatagramPacket Methods
InetAddress getAddress() byte[] getData() int getLength() int getPort() void setAddress(InetAddress addr) void setData(byte[] buffer) void setLength(int length) void setPort(int port)
24
DatagramSocket Class The DatagramSocket class provides access to a UDP socket, which allows UDP packets to be sent and received. The same DatagramSocket can be used to receive as well as to send packets. Read operations are blocking - i.e. the application will continue to wait until a packet arrives.
25
Each DatagramSocket binds to a port on the local machine
Each DatagramSocket binds to a port on the local machine. The port number need not match the port number of the remote machine. If the application is a UDP server, it will usually bind to a specific port number.
26
Creating a DatagramSocket
Constructor to use for creating a client DatagramSocket: DatagramSocket() throws java.net.SocketException Example: DatagramSocket socket; try { socket = new DatagramSocket(); } catch (SocketException exception) { … }
27
Constructor to use for creating a server DatagramSocket:
DatagramSocket(int port) throws java.net.SocketException Example: DatagramSocket socket; try { socket = new DatagramSocket(2000); } catch (SocketException exception) { … }
28
DatagramSocket Methods
void close() void connect(InetAddress r_addr, int r_port) void disconnect() InetAddress getInetAddress() int getPort() InetAddress getLocalAddress() int getLocalPort() int getReceiveBufferSize() throws java.net.SocketException
29
int getSoTimeout() throws java.net.SocketException
int getSendBufferSize() throws java.net.SocketException int getSoTimeout() throws java.net.SocketException void receive(DatagramPacket packet) throws java.io.IOException void send(DatagramPacket packet) throws java.io.IOException int setReceiveBufferSize(int length) throws java.net.SocketException int setSendBufferSize(int length) throws java.net.SocketException void setSoTimeout(int duration) throws java.net.SocketException
30
Listening for UDP Packets
Before an application can read UDP packets, it must bind a socket to a local UDP port using DatagramSocket create a DatagramPacket that will contain the data.
31
Packet DatagramSocket DatagramPacket UDP application Reads packets
Translates packets Into a DatagramPacket UDP application
32
The following code illustrates the process for reading UDP packets.
DatagramPacket packet; DatagramSocket socket; packet = new DatagramPacket(new byte[256], 256); socket = new DatagramSocket(2000); boolean finished = false; while (!finished) { socket.receive(packet); // process the packet } socket.close();
33
ByteArrayInputStream
Java I/O streams are usually used to access the contents of the byte array in a DatagramPacket. See example later. ByteArrayInputStream DatagramPacket DataInputStream IP address (java.net.InetAddr) Port address (int) Packet data (byte[]) UDP application
34
Sending UDP Packets When sending a packet, the application must create a DatagramPacket that will contain the data. The address and port information must also be set. When the packet is ready for transmission, the send method of DatagramSocket should be invoked.
35
DatagramSocket UDP application Packet DatagramPacket Binds to a
UDP port UDP application Send DatagramPacket using DatagramSocket Packet Constructs packet DatagramPacket
36
The following code illustrates the process for sending UDP packets.
DatagramPacket packet; DatagramSocket socket; packet = new DatagramPacket(new byte[256], 256); socket = new DatagramSocket(2000); packet.setAddress(…); packet.setPort(2000); boolean finished = false; while (!finished) { // write data to packet buffer socket.send(packet); … } socket.close();
37
User Datagram Protocol Example
Run receiving application java PacketReceiveDemo Run sending application java PacketSendDemo
42
ByteArrayOutputStream
PacketSendDemo PrintStream print(str) ByteArrayOutputStream DatagramPacket toByteArray() send(packet) DatagramSocket
43
ByteArrayInputStream
DatagramSocket receive(packet) ByteArrayInputStream DatagramPacket getData() read() PacketReceiveDemo
44
Building a UDP Client/Server
Run echo server java EchoServer Run echo client java EchoClient
45
Algorithm for Echo Server
Create socket Create an empty packet Repeat the following forever Wait for a packet Send the packet back to sender
46
Algorithm for Echo Client
Create socket Set timeout value for socket Repeat the following ten times Create the message to be sent Create packet containing the message as well as the destination IP and the port Send the packet through socket Wait for packet from receiver through socket or timeout if packet received Create an input stream to access data in the packet Use the input stream to read the data and then display it on the screen. Sleep for a second
47
Overcoming UDP Limitations
Lack of Guaranteed Delivery Lack of Guaranteed Packet Sequencing Lack of Flow Control
48
Lack of Guaranteed Delivery
Packets sent via UDP may become lost in transit. UDP packets can also become damaged or lost. For some applications, the loss of individual packets may not have a noticeable effect (e.g. video streams). For other applications, loss of packets is not acceptable (e.g. file transfers).
49
If guaranteed delivery is required,
avoid packet-based communication, and use a more suitable transport mechanism (e.g. TCP). send acknowledgement to sender after receiving packets.
50
Lack of Guaranteed Packet Sequencing
Applications that require sequential access to data should include a sequence number in the contents of a datagram packet. This enables detection of duplicate packets and also missing packets.
51
Lack of Flow Control The technique of flow control is important to avoid flooding a system with more data than it can handle due to limited bandwidth. One technique of flow control is to limit the number of unacknowledged packets. E.g.: increase control when number of acknowledgement packets received is much less than the number of packets sent.
52
Transmission Control Protocol
53
Overview Unlike UDP which is concerned with the transmission of packets of data, TCP establishes a "virtual connection" between two machines through which streams of data may be sent. TCP guarantees delivery and order, providing a reliable byte communication stream between client and server that supports two-way communication.
54
Establish a virtual connection
Transmit data back and forth Terminate the connection
55
TCP uses IP (Internet Protocol) to establish the connection between machines.
This connection provides an interface that allows streams of bytes to be sent and received, and transparently converts the data into IP datagram packets. The virtual connection between two machines is represented by a socket.
56
TCP sockets are different from UDP sockets:
TCP sockets are connected to a single machine. UDP sockets only send and receive packets of data. TCP allows tansmission of data through byte streams. They are converted into datagram packets for transmission over the network without programmer intervention.
57
Advantages of TCP over UDP
Automatic Error Control Data transmission is more dependable. Delivery of data is guaranteed - lost data packets are retransmitted. By means of a timer, TCP retransmits a packet if an acknowledgement is not received from the recipient within a specified amount of time.
58
Reliability As packets are delivered by IP, they will frequently arrive out of order. However, each packet contains a sequence number. Using this sequence number and queuing out-of-order packets, TCP is able to pass arriving packets to the application in the correct sequence.
59
Ease of Use Network programmers will find programming communication via TCP sockets far simpler than via datagram packets. This is because data sent and received can be treated as a continuous stream (like I/O streams). The data need not be packaged into discrete units like UDP.
60
Communication Using Ports
Both UDP and TCP uses the concept of a communications port, which distinguishes one application from another. When a TCP socket establishes a connection to another machine, the following information will be required: the IP address of the remote machine the port number
61
Like ports in UDP, ports in TCP are also represented by a number in the range 1 - 65535.
Ports below 1024 are restricted to use by well-known services. For example, Telnet (port 23) SMTP (port 25) HTTP (port 80) POP3 (port 110)
62
Socket Operations TCP sockets can perform a variety of operations:
Establish a connection to a remote host Send data to a remote host Receive data from a remote host Close a connection
63
There is a special type of socket that provides a service that will bind to a specific port number. Normally used only in servers, this socket can perform the following operations: Bind to a local port Accept incoming connections from remote hosts Unbind from a local port
64
TCP and the Client/Server Paradigm
In network programming, applications that use sockets are divided into clients and servers. A client is software that initiates a connection and sends requests. A server is software that listens for connections and processes requests.
65
Note that in the context of UDP programming, no actual connection is established. UDP applications may both initiate and receive requests on the same socket. In the client/server paradigm, when there is a connection between two applications, one must be a client and the other must be a server.
66
Network Clients Network clients initiate connections and control network transactions. The server fulfills the requests of the client but not the other way round. The network client speaks to the server using a network protocol. E.g an HTTP client communicates with an HTTP server using HTTP.
67
Port numbers are used to enable clients to locate servers. E. g
Port numbers are used to enable clients to locate servers. E.g. a web server uses port 80.
68
Network Servers The role of the network server is to bind to a specific port and to listen for new connections. Unlike the client, the server must run continually in the hope that some client will want its services. The server runs indefinitely. Normally, it is automatically started when the host computer of the server is started.
69
Some servers can handle only one connection at a time, while others can handle many connections concurrently, through the use of threads. Some protocols (e.g. HTTP/1.0) normally allow only one request per connection. Others, like POP3, support a sequence of requests. Servers answer the client request by sending either a response or an error message.
70
TCP Sockets and Java Java provide the following classes for TCP sockets: java.net.Socket java.net.ServerSocket The Socket class should be used when writing client software. The ServerSocket class should be used when writing server software.
71
Socket Class Socket objects represent client sockets, and is a communication channel between two TCP communications ports belonging to one or two machines.
72
There are several constructors for the Socket class.
The easiest way to create a socket is shown below: Socket mySocket; try { mySocket = new Socket(" 80); } catch (Exception e) { … }
73
Some of the other constructors:
Socket(InetAddress addr, int port) Throws java.io.IOException, java.lang.SecurityException Socket(InetAddress rAddr, int rPort, InetAddress lAddr, int lPort) Socket(String rHost, int rPort, InetAddress lAddr, int lPort) Throws java.net.UnknownHostException, java.io.IOException, java.lang.SecurityException
74
Using a Socket Refer section (pg 150) for a description of some of the methods of the Socket class.
75
Reading from and Writing to TCP Sockets
In Java, once a socket is created, it is connected and ready to read/write by using the socket's input and output streams. Use the methods getInputStream() and getOutputStream() to access those streams.
76
Example: } catch (Exception e) { … } Socket socket;
InputStreamReader isr; BufferedReader br; PrintStream ps; try { socket = new Socket(" isr = new InputStreamReader(socket.getInputStream()); br = new BufferedReader(isr); ps = new PrintStream(socket.getOutputStream()); } catch (Exception e) { … }
77
SO_TIMEOUT Socket Option
Socket options are settings that modify how sockets work. They can affect the performance of applications. SO_TIMEOUT is the most useful socket option. It allows a timer to be started when a read request is made on a socket. When no data arrives in time and the timer expires, a java.io.InterruptedIOException is thrown which can be caught to check for a timeout.
78
Use the setSoTimeout() method to set the duration of the timer
Use the setSoTimeout() method to set the duration of the timer. Example: socket.setSoTimeout(5000); The getSoTimeout() method can be used to get the duration of the timer. A value of zero means that timeouts are disabled and read operations will block indefinitely.
79
Creating a TCP Server The given example is a TCP server which returns the current day and time to the client.
80
SocketServer Class The server socket is a special type of socket used to provide TCP services. Client sockets bind to any free port on the local machine, and connect to a specific port and host. The difference with server sockets is that they bind to a specific port on the local machine so that remote clients may locate a service.
81
Client socket connections will connect to only one machine, whereas server sockets are capable of fulfilling the requests of multiple clients.
82
Creating a ServerSocket
Once a server socket is created, it will be bound to a local port and ready to accept incoming connections. When clients attempt to connect, they are placed into a queue. When this queue is full, further clients are refused.
83
There are several constructors for the ServerSocket class.
The easiest way to create a socket is shown below: ServerSocket mySocket; try { mySocket = new ServerSocket(80); } catch (Exception e) { … }
84
Some of the other constructors:
ServerSocket(int port) Throws java.io.IOException, java.lang.SecurityException If port is 0, then any free port will be used. By default, the queue size is set to 50. ServerSocket(int port, int maxClients) Allocates sufficient space to the queue to support the specified number of client sockets.
85
Using a ServerSocket Refer section (pg 161-Reilly) for a description of some of the methods of the ServerSocket class. The most important method is the accept() method, which accepts client connection requests.
86
Accepting and Processing Requests from TCP Clients
The most important function of a server socket is to accept client sockets. Once a client socket is obtained, the server can perform all the "real work" of server programming, which involves reading from and writing to the socket to implement a network protocol. Example: a mail server that provides access to stored messages would listen to commands and send back message contents.
87
Example: ServerSocket server; BufferedReader reader;
PrintWriter writer; server = new ServerSocket(13); while (true) { Socket client = server.accept(); reader = new BufferedReader( new InputStreamReader( client.getInputStream())); writer = new PrintWriter( new OutputStreamWriter( client.getOutputStream())); … }
88
TCP Socket Client-Server : ALI BABA…
89
ALI BABA Client-Server
90
Client Application In this example, there are 2 java programs
The client program is implemented as a class NyietInSengClient
91
public class NyietInSengClient {
import java.io.*; import java.net.*; public class NyietInSengClient { public static void main(String[] args) throws IOException { Socket nisSocket = null; PrintWriter out = null; BufferedReader in = null; try { nisSocket = new Socket("localhost", 8888); out = new PrintWriter(nisSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(nisSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: localhost."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: localhost."); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String fromServer; String fromUser; while ((fromServer = in.readLine()) != null) { System.out.println("Server: " + fromServer); if (fromServer.equals("tata titi tutu")) break; fromUser = stdIn.readLine(); if (fromUser != null) { System.out.println("Client: " + fromUser); out.println(fromUser); } out.close(); in.close(); stdIn.close(); nisSocket.close();
92
Server Application Server application is implemented using 2 classes:
NyietInSengServer NyietInSengServer contains method main() for the server program. It listens at a port for incoming connection, accept the connection and reads messages from client/writes responses to the client through a socket
93
public class NyietInSengServer {
import java.net.*; import java.io.*; public class NyietInSengServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(8888); } catch (IOException e) { System.err.println("Could not listen on port: 8888."); System.exit(1); } Socket clientSocket = null; clientSocket = serverSocket.accept(); System.err.println("Accept failed."); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; NyietInSengProtocol nis = new NyietInSengProtocol(); outputLine = nis.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = nis.processInput(inputLine); if (outputLine.equals("tata titi tutu")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close();
94
Protocol class (part of server app)
NyietInSengProtocol NyietInSengProtocol provides the jokes. It tracks the current joke, the current status (SENTTOKTOK, SENTCLUE, etc) and returns joke text based on the current status. It implements a communication protocol (a language) agreed by the client and server.
95
Server App. Begins by creating a ServerSocket object to listen (wait) at a certain port. When selecting a port no., pick one that is not reserved for other services. NyietInSengServer waits at port 8888 as the port 8888 is not used in my computer environment: try { serverSocket = new ServerSocket(8888); } catch (IOException e) { System.out.println("Could not listen on port: 8888"); System.exit(-1);
96
Server App. The constructor for ServerSocket throws an exception if it fail to listen the specified port (say if it is being used) In this case NyietInSengServer has no other choice than to exit.
97
If the server is able to connect to the specified port, then a ServerSocket object is created and the server app. Will perform the following steps – accept connection from client (in bold): Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.out.println("Accept failed: 8888"); System.exit(-1); }
98
Server App. Method accept() waits until a client program is executed and requesting for connection at a specified host and port (example, host : localhost and port : 8888. When connection between the client and server is succesfully created, method accept() will return a new Socket object (in example :clientSocket) which is bound to a new port. NyietInSengServer can communicate with NyietInSengClient through this new socket. It can keep listening and waiting for new incoming connection using the original ServerSocket (in example : serverSocket) However, in the example, the server application is not able to cater for more than 1 client.
99
Read/Write Process Gets the socket's input and output stream and opens readers and writers on them PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader( clientSocket.getInputStream())); String inputLine, outputLine;
100
Server App. After the server successfully establishes a connection with a client, it communicates with the client using this code: // initiate conversation with client NyietInSengProtocol nis = new NyietInSengProtocol(); outputLine = nis.processInput(null); out.println(outputLine); Initiates communication with the client by writing to the socket (shown in bold).
101
Server App. while ((inputLine = in.readLine()) != null) {
outputLine = nis.processInput(inputLine); out.println(outputLine); if outputLine.equals(“tata titi tutu")) break; } Communicates with the client by reading from and writing to the socket (the while loop).
102
1 is already familiar. Step 2 is shown in bold and is worth a few comments.
After the NyietInSengProtocol is created, the code calls NyietInSengProtocol 's processInput method to get the first message that the server sends to the client. For this example, the first thing that the server says is “NyietInSeng MatekAji Semar Ngiseng!" Next, the server writes the information to the PrintWriter connected to the client socket, thereby sending the message to the client.
103
Communication Protocol of AliBaba Client-Server
Following is the implementation of the protocol:
104
public class NyietInSengProtocol {
import java.net.*; import java.io.*; public class NyietInSengProtocol { private static final int WAITING = 0; private static final int SENTTOKTOK = 1; private static final int SENTCLUE = 2; private static final int ANOTHER = 3; private static final int NUMJOKES = 3; private int state = WAITING; private int currentJoke = 0; private String[] clues = { "Ali", "Di Sini", "Hari"}; private String[] answers = { "Ali Baba, Bujang Lapok la.. ", "Di Sini lah, Oi Di Sana! ", "Harimau Kuat! Grrrrrr "}; public String processInput(String theInput) { String theOutput = null; if (state == WAITING) { theOutput = "NyietInSeng MatekAji Semar Ngiseng!"; state = SENTTOKTOK; } else if (state == SENTTOKTOK) { if (theInput.equalsIgnoreCase("Siapa tu?")) { theOutput = clues[currentJoke]; state = SENTCLUE; } else { theOutput = "Sepatutnya awak cakap \"Siapa tu?\"! " + "Cuba lagi. NyietInSeng MatekAji Semar Ngiseng!"; } } else if (state == SENTCLUE) { if (theInput.equalsIgnoreCase(clues[currentJoke] + " mana?")) { theOutput = answers[currentJoke] + " Main lagi? (y/n)"; state = ANOTHER; theOutput = "Sepatutnya awak cakap \"" + clues[currentJoke] + " mana?\"" + "! Cuba lagi. NyietInSeng MatekAji Semar Ngiseng!"; } else if (state == ANOTHER) { if (theInput.equalsIgnoreCase("y")) { if (currentJoke == (NUMJOKES - 1)) currentJoke = 0; else currentJoke++; theOutput = "tata titi tutu"; state = WAITING; return theOutput;
105
Socket-based Client-Server Application
Client-Server application architecture Choosing services – Connectionless atau Connection-oriented
106
Evolution of Application Architecture
107
3-tier Client-server application architecture
108
Internet Protocol and Network Application
Internet protocol supports: General-purpose service for reliable data transmission Mechanism for connecting hosts Network application programs: Use Internet Protocol to connect to other application Provide user-level services
109
Client-Server Model Server Application acts as a “listener”
Waits for incoming messages Executes services Returns the results/outcomes Client Application makes connection Sends messages to the server Waits for response
110
Features of a Client An application program
Becomes a client when a network service is needed It can also executes other calculation Is directly created by the users Is executed locally by at the users’ computer Initiates connection to a server Able to access various services (at a given time) Does not require a special device or operating system
111
Features of a Server Special-purpose application for providing a network service Is executed on a remote computer (usually is centralised and shared) Waits and receives request for services from the clients Requires high-performance device and operating system
112
Transport Protocol and Client-Server
Client and server exchange messages via transport protocol such as TCP or UDP Both client and server must have the same protocol stack and both interact with the transport layer
113
Transport Protocol and Client-Server
114
Several Services on a Server
115
Identifying a Service Every service has a unique identifier which is used by the client and server Example - TCP uses port number protocol (port_num) as identifier Server is registered under a specific port number for a service Client asks for a session with the port number for the service Every transport session contains 2 unique indentifier (IP address, port number) at the server (IP address, port number) at the client
116
Connection-oriented and Connectionless Transport Protocol
Which one should be chosen? UDP - connectionless Client builds a message Client sends the message to a server The server responds Message must be loaded into a UDP datagram TCP - connection-oriented Client makes a connection to a server Client and server exchange messages Client terminates the connection
117
UDP UDP is a connectionless transport protocol, i.e. it doesn't guarantee either packet delivery or that packets arrive in sequential order. With UDP, bytes of data are grouped together in discrete packets which are sent over the network.
118
No two packets are guaranteed the same route.
Packets may travel along different paths depending on the state of the network. No two packets are guaranteed the same route. Each packet has a time-to-live (TTL) counter, which is updated when it is routed along to the next point in the network. When the timer expires, it will be discarded, and the recipient will not be notified.
119
If a packet does arrive, it will always arrive intact
If a packet does arrive, it will always arrive intact. Packets that are corrupt or only partially delivered are discarded.
120
Advantages of UDP UDP communication can be more efficient than guaranteed-delivery data streams. Unlike TCP streams, which establish a connection, UDP causes fewer overheads. Real-time applications that demand up-to-the-second or better performance may be candidates for UDP, as there are fewer delays due to error checking and flow control of TCP.
121
UDP sockets can receive data from more than one host machine.
Some network protocols specify UDP as the transport mechanism.
122
Java Support for UDP Two classes are provided:
DatagramPacket class (java.net) DatagramSocket class (java.net)
123
DatagramPacket Class A DatagramPacket object represents a data packet intended for transmission using UDP. It contains addressing information such as an IP address and a port. When a DatagramPacket is read from a UDP socket, the IP address/port number of the packet represents the address/port number of the sender.
124
When a DatagramPacket is used to send a UDP packet, the IP address/port represents the address/port of the recipient. DatagramPacket IP address (java.net.InetAddr) Port address (int) Packet data (byte[])
125
Creating a DatagramPacket
Constructor to use for creating a DatagramPacket for receiving incoming UDP packets: DatagramPacket(byte[] buffer, int length) Example: DatagramPacket packet; packet = new DatagramPacket(new byte[256], 256);
126
Constructor to use for sending a DatagramPacket to a remote machine
DatagramPacket(byte[] buffer, int length, InetAddress dest_addr, int dest_port) Example: DatagramPacket packet; InetAddress addr; addr = InetAddress.getByName(" "); packet = new DatagramPacket(new byte[128], ,addr, 2000);
127
DatagramPacket Methods
InetAddress getAddress() byte[] getData() int getLength() int getPort() void setAddress(InetAddress addr) void setData(byte[] buffer) void setLength(int length) void setPort(int port)
128
DatagramSocket Class The DatagramSocket class provides access to a UDP socket, which allows UDP packets to be sent and received. The same DatagramSocket can be used to receive as well as to send packets. Read operations are blocking - i.e. the application will continue to wait until a packet arrives.
129
Each DatagramSocket binds to a port on the local machine
Each DatagramSocket binds to a port on the local machine. The port number need not match the port number of the remote machine. If the application is a UDP server, it will usually bind to a specific port number.
130
Creating a DatagramSocket
Constructor to use for creating a client DatagramSocket: DatagramSocket() throws java.net.SocketException Example: DatagramSocket socket; try { socket = new DatagramSocket(); } catch (SocketException exception) { … }
131
Constructor to use for creating a server DatagramSocket:
DatagramSocket(int port) throws java.net.SocketException Example: DatagramSocket socket; try { socket = new DatagramSocket(2000); } catch (SocketException exception) { … }
132
DatagramSocket Methods
void close() void connect(InetAddress r_addr, int r_port) void disconnect() InetAddress getInetAddress() int getPort() InetAddress getLocalAddress() int getLocalPort() int getReceiveBufferSize() throws java.net.SocketException
133
int getSoTimeout() throws java.net.SocketException
int getSendBufferSize() throws java.net.SocketException int getSoTimeout() throws java.net.SocketException void receive(DatagramPacket packet) throws java.io.IOException void send(DatagramPacket packet) throws java.io.IOException int setReceiveBufferSize(int length) throws java.net.SocketException int setSendBufferSize(int length) throws java.net.SocketException void setSoTimeout(int duration) throws java.net.SocketException
134
Listening for UDP Packets
Before an application can read UDP packets, it must bind a socket to a local UDP port using DatagramSocket create a DatagramPacket that will contain the data.
135
Packet DatagramSocket DatagramPacket UDP application Reads packets
Translates packets Into a DatagramPacket UDP application
136
The following code illustrates the process for reading UDP packets.
DatagramPacket packet; DatagramSocket socket; packet = new DatagramPacket(new byte[256], 256); socket = new DatagramSocket(2000); boolean finished = false; while (!finished) { socket.receive(packet); // process the packet } socket.close();
137
ByteArrayInputStream
Java I/O streams are usually used to access the contents of the byte array in a DatagramPacket. See example later. ByteArrayInputStream DatagramPacket DataInputStream IP address (java.net.InetAddr) Port address (int) Packet data (byte[]) UDP application
138
Sending UDP Packets When sending a packet, the application must create a DatagramPacket that will contain the data. The address and port information must also be set. When the packet is ready for transmission, the send method of DatagramSocket should be invoked.
139
DatagramSocket UDP application Packet DatagramPacket Binds to a
UDP port UDP application Send DatagramPacket using DatagramSocket Packet Constructs packet DatagramPacket
140
The following code illustrates the process for sending UDP packets.
DatagramPacket packet; DatagramSocket socket; packet = new DatagramPacket(new byte[256], 256); socket = new DatagramSocket(2000); packet.setAddress(…); packet.setPort(2000); boolean finished = false; while (!finished) { // write data to packet buffer socket.send(packet); … } socket.close();
141
User Datagram Protocol Example
Run receiving application java PacketReceiveDemo Run sending application java PacketSendDemo
146
ByteArrayOutputStream
PacketSendDemo PrintStream print(str) ByteArrayOutputStream DatagramPacket toByteArray() send(packet) DatagramSocket
147
ByteArrayInputStream
DatagramSocket receive(packet) ByteArrayInputStream DatagramPacket getData() read() PacketReceiveDemo
148
Building a UDP Client/Server
Run echo server java EchoServer Run echo client java EchoClient
149
Algorithm for Echo Server
Create socket Create an empty packet Repeat the following forever Wait for a packet Send the packet back to sender
150
Algorithm for Echo Client
Create socket Set timeout value for socket Repeat the following ten times Create the message to be sent Create packet containing the message as well as the destination IP and the port Send the packet through socket Wait for packet from receiver through socket or timeout if packet received Create an input stream to access data in the packet Use the input stream to read the data and then display it on the screen. Sleep for a second
151
Overcoming UDP Limitations
Lack of Guaranteed Delivery Lack of Guaranteed Packet Sequencing Lack of Flow Control
152
Lack of Guaranteed Delivery
Packets sent via UDP may become lost in transit. UDP packets can also become damaged or lost. For some applications, the loss of individual packets may not have a noticeable effect (e.g. video streams). For other applications, loss of packets is not acceptable (e.g. file transfers).
153
If guaranteed delivery is required,
avoid packet-based communication, and use a more suitable transport mechanism (e.g. TCP). send acknowledgement to sender after receiving packets.
154
Lack of Guaranteed Packet Sequencing
Applications that require sequential access to data should include a sequence number in the contents of a datagram packet. This enables detection of duplicate packets and also missing packets.
155
Lack of Flow Control The technique of flow control is important to avoid flooding a system with more data than it can handle due to limited bandwidth. One technique of flow control is to limit the number of unacknowledged packets. E.g.: increase control when number of acknowledgement packets received is much less than the number of packets sent.
156
Transmission Control Protocol
157
Overview Unlike UDP which is concerned with the transmission of packets of data, TCP establishes a "virtual connection" between two machines through which streams of data may be sent. TCP guarantees delivery and order, providing a reliable byte communication stream between client and server that supports two-way communication.
158
Establish a virtual connection
Transmit data back and forth Terminate the connection
159
TCP uses IP (Internet Protocol) to establish the connection between machines.
This connection provides an interface that allows streams of bytes to be sent and received, and transparently converts the data into IP datagram packets. The virtual connection between two machines is represented by a socket.
160
TCP sockets are different from UDP sockets:
TCP sockets are connected to a single machine. UDP sockets only send and receive packets of data. TCP allows tansmission of data through byte streams. They are converted into datagram packets for transmission over the network without programmer intervention.
161
Advantages of TCP over UDP
Automatic Error Control Data transmission is more dependable. Delivery of data is guaranteed - lost data packets are retransmitted. By means of a timer, TCP retransmits a packet if an acknowledgement is not received from the recipient within a specified amount of time.
162
Reliability As packets are delivered by IP, they will frequently arrive out of order. However, each packet contains a sequence number. Using this sequence number and queuing out-of-order packets, TCP is able to pass arriving packets to the application in the correct sequence.
163
Ease of Use Network programmers will find programming communication via TCP sockets far simpler than via datagram packets. This is because data sent and received can be treated as a continuous stream (like I/O streams). The data need not be packaged into discrete units like UDP.
164
Communication Using Ports
Both UDP and TCP uses the concept of a communications port, which distinguishes one application from another. When a TCP socket establishes a connection to another machine, the following information will be required: the IP address of the remote machine the port number
165
Like ports in UDP, ports in TCP are also represented by a number in the range 1 - 65535.
Ports below 1024 are restricted to use by well-known services. For example, Telnet (port 23) SMTP (port 25) HTTP (port 80) POP3 (port 110)
166
Socket Operations TCP sockets can perform a variety of operations:
Establish a connection to a remote host Send data to a remote host Receive data from a remote host Close a connection
167
There is a special type of socket that provides a service that will bind to a specific port number. Normally used only in servers, this socket can perform the following operations: Bind to a local port Accept incoming connections from remote hosts Unbind from a local port
168
TCP and the Client/Server Paradigm
In network programming, applications that use sockets are divided into clients and servers. A client is software that initiates a connection and sends requests. A server is software that listens for connections and processes requests.
169
Note that in the context of UDP programming, no actual connection is established. UDP applications may both initiate and receive requests on the same socket. In the client/server paradigm, when there is a connection between two applications, one must be a client and the other must be a server.
170
Network Clients Network clients initiate connections and control network transactions. The server fulfills the requests of the client but not the other way round. The network client speaks to the server using a network protocol. E.g an HTTP client communicates with an HTTP server using HTTP.
171
Port numbers are used to enable clients to locate servers. E. g
Port numbers are used to enable clients to locate servers. E.g. a web server uses port 80.
172
Network Servers The role of the network server is to bind to a specific port and to listen for new connections. Unlike the client, the server must run continually in the hope that some client will want its services. The server runs indefinitely. Normally, it is automatically started when the host computer of the server is started.
173
Some servers can handle only one connection at a time, while others can handle many connections concurrently, through the use of threads. Some protocols (e.g. HTTP/1.0) normally allow only one request per connection. Others, like POP3, support a sequence of requests. Servers answer the client request by sending either a response or an error message.
174
TCP Sockets and Java Java provide the following classes for TCP sockets: java.net.Socket java.net.ServerSocket The Socket class should be used when writing client software. The ServerSocket class should be used when writing server software.
175
Socket Class Socket objects represent client sockets, and is a communication channel between two TCP communications ports belonging to one or two machines.
176
There are several constructors for the Socket class.
The easiest way to create a socket is shown below: Socket mySocket; try { mySocket = new Socket(" 80); } catch (Exception e) { … }
177
Some of the other constructors:
Socket(InetAddress addr, int port) Throws java.io.IOException, java.lang.SecurityException Socket(InetAddress rAddr, int rPort, InetAddress lAddr, int lPort) Socket(String rHost, int rPort, InetAddress lAddr, int lPort) Throws java.net.UnknownHostException, java.io.IOException, java.lang.SecurityException
178
Using a Socket Refer section (pg 150) for a description of some of the methods of the Socket class.
179
Reading from and Writing to TCP Sockets
In Java, once a socket is created, it is connected and ready to read/write by using the socket's input and output streams. Use the methods getInputStream() and getOutputStream() to access those streams.
180
Example: } catch (Exception e) { … } Socket socket;
InputStreamReader isr; BufferedReader br; PrintStream ps; try { socket = new Socket(" isr = new InputStreamReader(socket.getInputStream()); br = new BufferedReader(isr); ps = new PrintStream(socket.getOutputStream()); } catch (Exception e) { … }
181
SO_TIMEOUT Socket Option
Socket options are settings that modify how sockets work. They can affect the performance of applications. SO_TIMEOUT is the most useful socket option. It allows a timer to be started when a read request is made on a socket. When no data arrives in time and the timer expires, a java.io.InterruptedIOException is thrown which can be caught to check for a timeout.
182
Use the setSoTimeout() method to set the duration of the timer
Use the setSoTimeout() method to set the duration of the timer. Example: socket.setSoTimeout(5000); The getSoTimeout() method can be used to get the duration of the timer. A value of zero means that timeouts are disabled and read operations will block indefinitely.
183
Creating a TCP Server The given example is a TCP server which returns the current day and time to the client.
184
SocketServer Class The server socket is a special type of socket used to provide TCP services. Client sockets bind to any free port on the local machine, and connect to a specific port and host. The difference with server sockets is that they bind to a specific port on the local machine so that remote clients may locate a service.
185
Client socket connections will connect to only one machine, whereas server sockets are capable of fulfilling the requests of multiple clients.
186
Creating a ServerSocket
Once a server socket is created, it will be bound to a local port and ready to accept incoming connections. When clients attempt to connect, they are placed into a queue. When this queue is full, further clients are refused.
187
There are several constructors for the ServerSocket class.
The easiest way to create a socket is shown below: ServerSocket mySocket; try { mySocket = new ServerSocket(80); } catch (Exception e) { … }
188
Some of the other constructors:
ServerSocket(int port) Throws java.io.IOException, java.lang.SecurityException If port is 0, then any free port will be used. By default, the queue size is set to 50. ServerSocket(int port, int maxClients) Allocates sufficient space to the queue to support the specified number of client sockets.
189
Using a ServerSocket Refer section (pg 161-Reilly) for a description of some of the methods of the ServerSocket class. The most important method is the accept() method, which accepts client connection requests.
190
Accepting and Processing Requests from TCP Clients
The most important function of a server socket is to accept client sockets. Once a client socket is obtained, the server can perform all the "real work" of server programming, which involves reading from and writing to the socket to implement a network protocol. Example: a mail server that provides access to stored messages would listen to commands and send back message contents.
191
Example: ServerSocket server; BufferedReader reader;
PrintWriter writer; server = new ServerSocket(13); while (true) { Socket client = server.accept(); reader = new BufferedReader( new InputStreamReader( client.getInputStream())); writer = new PrintWriter( new OutputStreamWriter( client.getOutputStream())); … }
192
TCP Socket Client-Server : ALI BABA…
193
ALI BABA Client-Server
194
Client Application In this example, there are 2 java programs
The client program is implemented as a class NyietInSengClient
195
public class NyietInSengClient {
import java.io.*; import java.net.*; public class NyietInSengClient { public static void main(String[] args) throws IOException { Socket nisSocket = null; PrintWriter out = null; BufferedReader in = null; try { nisSocket = new Socket("localhost", 8888); out = new PrintWriter(nisSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(nisSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: localhost."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: localhost."); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String fromServer; String fromUser; while ((fromServer = in.readLine()) != null) { System.out.println("Server: " + fromServer); if (fromServer.equals("tata titi tutu")) break; fromUser = stdIn.readLine(); if (fromUser != null) { System.out.println("Client: " + fromUser); out.println(fromUser); } out.close(); in.close(); stdIn.close(); nisSocket.close();
196
Server Application Server application is implemented using 2 classes:
NyietInSengServer NyietInSengServer contains method main() for the server program. It listens at a port for incoming connection, accept the connection and reads messages from client/writes responses to the client through a socket
197
public class NyietInSengServer {
import java.net.*; import java.io.*; public class NyietInSengServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(8888); } catch (IOException e) { System.err.println("Could not listen on port: 8888."); System.exit(1); } Socket clientSocket = null; clientSocket = serverSocket.accept(); System.err.println("Accept failed."); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; NyietInSengProtocol nis = new NyietInSengProtocol(); outputLine = nis.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = nis.processInput(inputLine); if (outputLine.equals("tata titi tutu")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close();
198
Protocol class (part of server app)
NyietInSengProtocol NyietInSengProtocol provides the jokes. It tracks the current joke, the current status (SENTTOKTOK, SENTCLUE, etc) and returns joke text based on the current status. It implements a communication protocol (a language) agreed by the client and server.
199
Server App. Begins by creating a ServerSocket object to listen (wait) at a certain port. When selecting a port no., pick one that is not reserved for other services. NyietInSengServer waits at port 8888 as the port 8888 is not used in my computer environment: try { serverSocket = new ServerSocket(8888); } catch (IOException e) { System.out.println("Could not listen on port: 8888"); System.exit(-1);
200
Server App. The constructor for ServerSocket throws an exception if it fail to listen the specified port (say if it is being used) In this case NyietInSengServer has no other choice than to exit.
201
If the server is able to connect to the specified port, then a ServerSocket object is created and the server app. Will perform the following steps – accept connection from client (in bold): Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.out.println("Accept failed: 8888"); System.exit(-1); }
202
Server App. Method accept() waits until a client program is executed and requesting for connection at a specified host and port (example, host : localhost and port : 8888. When connection between the client and server is succesfully created, method accept() will return a new Socket object (in example :clientSocket) which is bound to a new port. NyietInSengServer can communicate with NyietInSengClient through this new socket. It can keep listening and waiting for new incoming connection using the original ServerSocket (in example : serverSocket) However, in the example, the server application is not able to cater for more than 1 client.
203
Read/Write Process Gets the socket's input and output stream and opens readers and writers on them PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader( clientSocket.getInputStream())); String inputLine, outputLine;
204
Server App. After the server successfully establishes a connection with a client, it communicates with the client using this code: // initiate conversation with client NyietInSengProtocol nis = new NyietInSengProtocol(); outputLine = nis.processInput(null); out.println(outputLine); Initiates communication with the client by writing to the socket (shown in bold).
205
Server App. while ((inputLine = in.readLine()) != null) {
outputLine = nis.processInput(inputLine); out.println(outputLine); if outputLine.equals(“tata titi tutu")) break; } Communicates with the client by reading from and writing to the socket (the while loop).
206
1 is already familiar. Step 2 is shown in bold and is worth a few comments.
After the NyietInSengProtocol is created, the code calls NyietInSengProtocol 's processInput method to get the first message that the server sends to the client. For this example, the first thing that the server says is “NyietInSeng MatekAji Semar Ngiseng!" Next, the server writes the information to the PrintWriter connected to the client socket, thereby sending the message to the client.
207
Communication Protocol of AliBaba Client-Server
Following is the implementation of the protocol:
208
public class NyietInSengProtocol {
import java.net.*; import java.io.*; public class NyietInSengProtocol { private static final int WAITING = 0; private static final int SENTTOKTOK = 1; private static final int SENTCLUE = 2; private static final int ANOTHER = 3; private static final int NUMJOKES = 3; private int state = WAITING; private int currentJoke = 0; private String[] clues = { "Ali", "Di Sini", "Hari"}; private String[] answers = { "Ali Baba, Bujang Lapok la.. ", "Di Sini lah, Oi Di Sana! ", "Harimau Kuat! Grrrrrr "}; public String processInput(String theInput) { String theOutput = null; if (state == WAITING) { theOutput = "NyietInSeng MatekAji Semar Ngiseng!"; state = SENTTOKTOK; } else if (state == SENTTOKTOK) { if (theInput.equalsIgnoreCase("Siapa tu?")) { theOutput = clues[currentJoke]; state = SENTCLUE; } else { theOutput = "Sepatutnya awak cakap \"Siapa tu?\"! " + "Cuba lagi. NyietInSeng MatekAji Semar Ngiseng!"; } } else if (state == SENTCLUE) { if (theInput.equalsIgnoreCase(clues[currentJoke] + " mana?")) { theOutput = answers[currentJoke] + " Main lagi? (y/n)"; state = ANOTHER; theOutput = "Sepatutnya awak cakap \"" + clues[currentJoke] + " mana?\"" + "! Cuba lagi. NyietInSeng MatekAji Semar Ngiseng!"; } else if (state == ANOTHER) { if (theInput.equalsIgnoreCase("y")) { if (currentJoke == (NUMJOKES - 1)) currentJoke = 0; else currentJoke++; theOutput = "tata titi tutu"; state = WAITING; return theOutput;
209
Web-based Client-Server Application
Server-side programming Servlet 209
210
SERVLET
211
Where are we? JAVA Object-oriented design Introduction Advanced topics
Server-side coding 10. JDBC 4. Object Classes 1. Intro to Java, Course 7. Inheritance 11.Streams 2. Java lang. basics 6. Exception Handling 13. Servlets 5. Encapsulation 14. JSP 3. Arrays 8. Polymorphism 12. Networking 9. Abstract classes and Interfaces Newbie Programmers Designers Developers Professionals
212
Outline Concepts Features javax.servlet.Servlet
Example: get and send a page to client Example: post Image generating Session tracking Cookie, HttpSession, URL-rewriting Practical examples
213
Today’s buzzwords Applets Servlets Session tracking
Java programs capable of running within a web browser Servlets Java code running on server side Session tracking Keeping context information during a session of browsing related web pages
214
What is java servlet ? A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol. Servlet is an opposite of applet as a server-side applet. Applet is an application running on client while servlet is running on server.
215
What is Java Servlets? = Servlet
module run inside request/response-oriented server Browser Java-enabled Web Server Servlet Database HTML form Servlets are to Servers what Applets are to Browsers Servlet = Applet 1. 서블릿의 개념 - 서버측에서 클라이언트측의 요구를 받아 그에 대한 처리를 한 후 결과를 되돌리는 모듈이다. 2. 애플릿/서블릿 애플릿은 서버측에서 작성되었지만, 코드가 클라이언트로 다운로드되어 실행되는 반면, 서블릿은 서버 측에서 직접 실행되어 그 결과만 반환된다는 점에서 오히려 CGI와 비슷하다. 하지만,CGI보다는 요구와 결과를 처리하는 방법이 더 쉽다. 3. JDK의 기본 패키지가 아니다. 서블릿을 작성하려면, JDK외에 JSDK(98년 중반 현재 2.0까지 발표)를 다운로드받아야 한다. 4. 서블릿을 동작시키려면, 서블릿 실행을 처리할 수 있는 웹 서버 또한 존재해야 한다. Server Browser Substitute for CGI scripts easier to write and fast to run Not part of the core Java Framework
216
Example use of servlet Processing data POST over HTTPs using HTML form as purchase order or credit card data Allowing collaborative between people such as on-line conferencing Many servlet can chain together among Web servers to reduce load on one Web server.
217
Why Use Servlets ? One of the reasons that Java became popular is Applets. but there are problems with Applets Browser compatibility Download bandwidth Server-side Java the code is executed on the server side not the client side a dynamically loaded module that services requests from a Web server
218
Servlets (contd.) vs. Common Gateway Interface (CGI)
create new process for each request most platform independent CGI language - Perl start a new instance of interpreter for every request CGI runs in a completely separate process from the Web server vs. Server-Side JavaScript only available on certain web servers vs. Active Server Pages (ASP)
219
CGI Communication (traditional approach)
1. Web browser requset a response from CGI program. 2. Web server create CGI profile file that was contain information about CGI variable, server and CGI output file. 3. Web server starts CGI application and wait for its termination. 4. CGI program runs and writes the result to CGI output file and then terminates. 5. Web server reads from CGI output file and send back to Web browser.
220
Servlet Communication
Web browser request servlet by specified URL as Web server call service() method in ServletLoader class which will dynamically load a specified servlet name from a special directory call servlet.
221
Servlet vs CGI Servlet run as light weight thread in process.
CGI run as heavy weight process.
222
Advantage of servlet over CGI
PlatForm Independence Servlets can run on any platform. PERL also can be moved from platform to platform while CGI such as C are not portable. Performance Servlets only needs be loaded once, while CGI programs needs to be load for every request so that servlet should performs faster than CGI Security While CGI can do many insecure things, java provided security in language level.
223
Three Tier Applications.
224
Java Servlet Development Kit installation
225
Requirement for running java servlet
Java Servlet API A set of java classes. This is a Java Servlet Development Kit(JSDK) that can be download from JSDK allows most standard Web server such as Netscape servers, IIS, Apache and others to load servlets Java-enabled Web server There are many web server that support java virtual machine such as Java Web server by SUN, WebSite Pro V2.0 by O’Reilly and the latest version of World Wide Web Consortium’s free jigsaw Web Server.
226
Java Web Server (JWS) response request Servlet Java Web Server
227
Servlet Lifecycle Server loads Servlets - run init method
No Concurrency Issue Server runs init only once, not per request Server loads Servlets - run init method Servlets Accept Request from Clients and return Data back - run service method service must be thread-safe - multiple service method at a time if that is impossible, servlet must implement SingleThreadModel interface Server removes Servlets - run destroy method destroy must be thread-safe - when server runs destroy, other threads might be accessing shared resources Server reloads Servlets - run init method
228
A Typical Servlet Lifecycle
from Servlet Essential by Stefan Zeiger
229
Servlet class Example Interface Servlet
Define the standard way in which a network server will access a servlet. All servlet classes must (fundamentally) implement this interface. GenericServlet Defines a generic, protocol-independent servlet. For servlet that is not intended to use with Web server. To write an HTTP servlet for use on the Web, extend HttpServlet instead HttpServlet For Servlet that is intended to use with Web server. This class adds HTTP-specific to work with a Web server context
230
Servlet Structure All servlet classes and interfaces that form the API are found in the javax.servlet package. All servlets, no matter what type of server they are destined to be used with, implement the javax.servlet.Servlet interface. This interface defines the basic functionality that a servlet must possess
231
ServletConfig When the servlet first starts up, the system can pass specific initialization information to the servlet for possible processing via the init(...) method. Parameters are passed in using a key/value pairing, and two methods are provided to access this data: getInitParameter(...) and getInitParameterName().
232
ServletContext allows the servlet to interrogate the server about various pieces of environmental data Example : Many servers, particularly web servers, refer to files and resources as virtual files. However, this makes opening up files difficult, as the virtual file or alias needs to be mapped onto a real file. The ServletContext interface, for example, provides a method to convert an alias and real path file names.
233
ServletContext
234
GenericServlet The base class on which the majority of servlets are based is the GenericServlet class.
235
Interface Servlet class
void init(ServletConfig) Initialized the servlet when it is loaded into server (system). abstract void service(ServletRequest, ServletResponse) This is an abstract class so that it must be implemented by a subclass of GenericServlet class. A method that the servlet processes each client request destroy() This method is called when the server remove a servlet from memory.
236
ServletRequest
237
ServletRequest If, on the other hand, data is coming from a non-HTTP client, then the data may be coming in as a stream. The ServletInputStream can be used to read this stream. Additional information about the client that may be useful is the home network address from which it is sending. This information can be made available through the getRemoteAddr() and getRemoteHost() methods.
238
ServletResponse The most important method of this interface is the getOutputStream() method. This returns the ServletOutputStream, which can be used to provide any other preferred output stream class from the java.io package.
239
GenericServlet : Example
240
GenericServlet
241
Web-Based Servlet The developers at Java recognized the fact that the majority of servlets would be employed in the field of the Internet, with particular emphasis on the world wide web. The servlet API offers you a direct alternative to using CGI and Microsoft's Active Server Pages (ASP) to implement server-side solutions. To make coding servlets for the web relatively easy, a special HttpServlet class was developed. This provided methods to access the more common header fields found in the HTTP protocol.
242
HttpServlet class void doGet(HttpServletRequest, HttpServletResponse)
This method handle HTTP GET requests. void doPost(HttpServletRequest, HttpServletResponse) This method handle HTTP POST requests. The Form parameter are read via HttpServletRequest parameter. void service(HttpServletRequest, HttpServletResponse) This method can handle both GET and POST method. Normally, service() method used to overide one or both of the previous method void service(servletRequest,ServeletResponse) This method overides service() method of GenericServlet class
243
HttpServlet The HttpServlet, based on the GenericServlet class.
It provides an improved interface for dealing with HTTP-specific client requests. In addition to the service(...) method that is used to deal with all requests, seven additional methods exist for processing requests; doGet(...), doPost(...), doHead(...), doPut(...), doTrace(...), doOptions(...) , and doDelete(...).
244
Servlet Architecture Overview - HTTP servlets
IS-A Servlet interface Client GET POST doGet(ServletRequest req, ServletResponse res); ServletRequest ServletResponse ServletResponnse doPost(ServletRequest req, ServletResponse res); parameters, protocol, remote host, ServerInputStream(binary data etc..) mime type to reply,reply data, ServletOutputStream
245
HttpServlet Interface
246
ServletRequest Interface
This interface return information about parameter sent with the request. int getContentLength() String getContentType() String getProtocol() String getScheme() String getServerName() int getServerPort() String getRemoteAddr()
247
HttpServletRequest :
248
ServletRequest Interface(continued)
String getRemoteHost() String getRealPath(String path) ServletInputStream getInputStream() String getParameter(String name) String[] getParameterValues(String name) Enumeration getParameterNames() Object getAttribute(String name)
249
ServletResponse Interface
This interface defined method for sending information back to Web browser. void setContentLength(int len) void setContentType(String type) ServletOutputStream getOutputStream()
250
HttpServletRequest Interface
The method of HttpServletRequest interface inherits the method in ServletRequest interface. GET, POST, and HEAD in HTTP are also supported.
251
Servlets (contd.) HttpServletRequest HttpServletResponse
information sent from the client getParameter() getParameterValues() getParameterNames() will discuss in detail later in FormPost HttpServletResponse information sent to the client getWriter() return an instance of PrintWriter you can use print and println with a PrintWriter see SimpleServlet
252
HttpServletResponse Interface(continued)
boolean containHeader(String name) void setStatus(int statusCode, String statusMessage) void sendError(int statusCode, String Message) void sendError(int statusCode) void setDateHeader(String name, long date) void sendRedirect(String location)
253
HttpServletResponse Interface
String getMethod() String getServletPath() String getPathInfo() String getPathTranslated() String getQueryString() String getRemoteUser() String getAuthType String getHeader(String name) String getIntHeader(String name) long getDateHeader() Enumeration getHeaderNames()
254
Writing the Servlet Implement the javax.servlet.Servlet interface
HTTP: extends javax.servlet.http.HttpServlet class public class SurveyServlet extends HttpServlet { /* typical servlet code, with no threading concerns * in the service method. */ ... }
255
Interacting with Clients(1) - HTTP servlets
methods doGet Get Client Post doPost Put doPut Delete doDelete HttpServletRequest - argument & HTTP header data String[] getParameterValues(String name) - get user parameter For GET method - String getQueryString() For POST, PUT, DELETE method - BufferedReader getReader() - text data - ServletInputStream getInputStream() - binary data
256
Interacting with Clients(2) - HTTP servlets
HttpServletResponse - return the response data to the user PrintWriter getWriter() - text data ServletOutputStream getOutputStream() - binary data Before accessing the Writer or OutputStream, HTTP header data should be set
257
Example of an HTTP Servlet - GET/HEAD methods
public class SimpleServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // set header field first res.setContentType("text/html"); // then get the writer and write the response data PrintWriter out = res.getWriter(); out.println("<HEAD><TITLE> SimpleServlet</TITLE></HEAD> <BODY>"); out.println("<h1> SimpleServlet Output </h1>"); out.println("</BODY>"); out.close(); } public String getServletInfo() { return "A simple servlet"; } }
258
Example (2) use of HttpServlet
259
Accessing web-based servlets
Assume the servlets' class file has been placed in the server's servlets directory. The servlet can be called by including /servlet/ before the servlet name in the URL. For example, if you set the class name of the sample servlet to TestServlet, then it could be accessed using
260
Apache-Tomcat Directory Structure
262
Starting Tomcat
264
Email database example : emaildb.html
<head> <title> DB Example</title> <meta http-equiv="Content-Type" content="text/html; charset=iso "> </head> <body bgcolor="#FFFFFF" text="#000000"> <form name="form1" method="get" action=" <p>Nama <input type="text" name="name" width = "20"> </p> <p> <input type="text" name=" " width="30"> <p> WebSite Address <input type="text" name="website" width="30"> <p> <input type="submit" name="submit" value="Submit"> <input type="reset" name="reset" value="Reset"> </form> </body> </html>
265
HTML Form Example
266
Saving data to emaildb – inserttodb servlet
/* Servlet to JDBC - save into database */ import java.io.*; import java.util.Enumeration; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.net.*; public class inserttodb extends HttpServlet{ static final String dbURI = "jdbc:mysql:/// db"; String str = "INSERT INTO list VALUES(?, ?, ?)"; Connection theConnection = null; private ServletConfig config; public void init(ServletConfig config) throws ServletException{ this.config=config; }
267
throws ServletException, IOException {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String nameS = request.getParameter("name"); String S = request.getParameter(" "); String websiteS = request.getParameter("website"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML><HEAD><TITLE> List.</TITLE>"); out.println("</HEAD>"); out.println("<BODY bgColor=blanchedalmond text=# topMargin=0>"); out.println("<P align=center><FONT face=Helvetica><FONT color=fuchsia style=\"BACKGROUND-COLOR: white\"><BIG><BIG>Save these data to database.</BIG></BIG></FONT></P>"); out.println("<P align=center>"); out.println("<form name=form1 action=\" out.println("<p>"); out.println("<input type=submit name=\"submit\" value=\"Retrieve Data\">"); out.println("</p>"); out.println("</form>");
268
// Load database driver Class.forName("org.gjt.mm.mysql.Driver");
try { // Load database driver Class.forName("org.gjt.mm.mysql.Driver"); } catch (ClassNotFoundException cnfe){ System.out.println("ClassNot found error"); }; // Create a Connection to db Data source theConnection = DriverManager.getConnection(dbURI); //Connect to db Data source } catch (SQLException sqle) { System.out.println(sqle); // prepare statement for inserting data into table PreparedStatement theStatement=theConnection.prepareStatement(str); //Set parameters for INSERT statement and execute it theStatement.setString(1, nameS); theStatement.setString(2, S); theStatement.setString(3, websiteS); theStatement.executeUpdate(); theConnection.close(); //Close database Connection } catch(Exception e){ out.println(e.getMessage());//Print trapped error. }
269
Saving to database and use a button to retrieve data back
270
Retrieve List from emaildb
271
Retrieve data from emaildb database
/* Servlet to retrieve data from database using JDBC */ import java.io.*; import java.util.Enumeration; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.net.*; public class dbServlet extends HttpServlet{ static final String dbURI = "jdbc:mysql:/// db"; Connection theConnection; private ServletConfig config; public void init(ServletConfig config) throws ServletException{ this.config=config; }
272
Continued public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession session = req.getSession(true); res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML><HEAD><TITLE> List.</TITLE>"); out.println("</HEAD>"); out.println("<BODY bgColor=blanchedalmond text=# topMargin=0>"); out.println("<P align=center><FONT face=Helvetica><FONT color=fuchsia style=\"BACKGROUND-COLOR: white\"><BIG><BIG>List of addresses.</BIG></BIG></FONT></P>"); out.println("<P align=center>"); out.println("<TABLE align=center border=1 cellPadding=1 cellSpacing=1 width=\"75%\">"); out.println("<TR>"); out.println("<TD>Name</TD>"); out.println("<TD> </TD>"); out.println("<TD>Website</TD></TR>");
273
Class.forName("org.gjt.mm.mysql.Driver");//Loading mysql Driver
try{ Class.forName("org.gjt.mm.mysql.Driver");//Loading mysql Driver theConnection = DriverManager.getConnection(dbURI); //Connect to db Statement theStatement=theConnection.createStatement(); ResultSet theResult=theStatement.executeQuery("select * from list"); while(theResult.next()) { //Fetch all the records and print in table out.println(); out.println("<TR>"); out.println("<TD>" + theResult.getString(1) + "</TD>"); out.println("<TD>" + theResult.getString(2) + "</TD>"); String s=theResult.getString(3); out.println("<TD><a href=" + s + ">" + s + "</a></TD>"); out.println("</TR>"); } theResult.close();//Close the result set theStatement.close();//Close statement theConnection.close(); //Close database Connection }catch(Exception e){ out.println(e.getMessage());//Print trapped error. out.println("</TABLE></P>"); out.println("<P> </P></FONT></BODY></HTML>"); public void destroy(){
274
Teknologi Rangkaian Komputer Lapisan Pengangkutan TCP/IP :
TK3133 Teknologi Rangkaian Komputer Lapisan Pengangkutan TCP/IP : TCP dan UDP
275
Unit Data Protokol Pengangkutan
276
Elemen Protokol Pengangkutan
Pengalamatan Pembinaan Sambungan Penamatan Sambungan Kawalan Aliran dan Penimbalan Pemultipleksan Pemulihan kerosakan
277
Protokol Pengangkutan
(a) Persekitaran Lapisan Pautan Data (b) Persekitaran Lapisan Pengangkutan
278
Pengalamatan
279
Pembinaan Sambungan Bagaimana sesuatu proses pada Hos 1 membina satu sambungan kepada server di Hos 2
280
Lapisan Pengangkutan TCP/IP
Internet Protocol (IP) menyediakan perkhidmatan datagram kurang/tidak- dipercayai di antara hos-hos Protokol Pengangkutan bertujuan untuk menyediakan pengangkutan data antara hujung ke hujung yang boleh dipercayai (juga kurang-dipercayai) dan kos efektif tanpa mengira jenis rangkaian Hujung ke hujung bermaksud proses ke proses atau aturcara
281
Lapisan Pengangkutan TCP/IP
Isu yang diambil-kira memeriksa integriti paket penghantaran semula paket yang rosak atau hilang penyediaan dan pengurusan sambungan Pengalamatan perlu mentakrifkan hos dan proses proses ditentukan oleh nombor pengkalan yang digunakan biasanya dalam pasangan <hos, pengkalan>
282
Perkhidmatan dan Protokol Pengangkutan dalam Internet
2 jenis perkhidmatan Internet dalam Lapisan Pengangkutan Berorientasikan sambungan / Connection oriented Tanpa sambungan / Connectionless 2 protokol pengangkutan yang utama : TCP (Transmission Control Protocol) UDP (User Datagram Protocol)
283
Transmission Control Protocol (TCP)
TCP ialah protokol pengangkutan yang paling kerap/popular digunakan Membekalkan penghantaran data yang dipercayai dengan menggunakan penghantaran datagram IP yang kurang dipercayai
284
Transmission Control Protocol (TCP)
TCP menjalankan fungsi lapisan pengangkutan yang biasa iaitu: Segmentation - pecahkan sesuatu utusan kepada paket-paket Membetulkan kesalahan - diperlukan kerana IP merupakan perkhidmatan yang tidak boleh dipercayai Kawalan point-to-point - untuk mengelakkan limpahan penimbal pemultipleks dan penyahmultipleks sesi
285
Protokol Kawalan Penghantaran (Transmission Control Protocol (TCP))
Perkhidmatan yang diberikan oleh TCP boleh dipercayai litar maya - berdasarkan orientasi-sambungan dupleks penuh - pindahan selari pada kedua-dua arah berpenimbal - TCP menerima data dan menghantarnya mengikut kesesuaian masa yang diperlukan
286
Pengalamatan dan Pemultipleksan TCP
Perkhidmatan TCP diperolehi dengan kedua-dua penghantar dan penerima mencipta soket Komputer yang berkomunikasi mesti setuju pada satu nombor pengkalan Pelayan buka pengkalan tertentu dan tungu mesej yang masuk Pelanggan/Klien pilih pengkalan tempatan dan hantar mesej kepada pengkalan yang dipilih
287
Pengalamatan dan Pemultipleksan TCP
TCP mengenali hubungan sebagai pasangan soket Alamat soket mengandungi alamat Internet dan nombor pengkalan Alamat Internet hos diberikan oleh IP Nombor pengkalan menentukan id pemprosesan pada hos
288
Pengalamatan dan Pemultipleksan TCP (samb)
Nombor Pengkalan boleh jadi dikhaskan (well-known port) atau diumpukkan secara dinamik. No. Pengkalan dibawah 256 adalah pengkalan well-known : untuk perkhidmatan piawai 23 untuk telnet, 25 untuk smtp, 80 untuk http, 21 untuk ftp Secara konsep, TCP boleh membuat hubungan secara multipleks ke beberapa soket pada sesuatu hos melalui satu sambungan lapisan rangkaian
289
Contoh Umpukan Pengkalan
Port Protocol Use 21 FTP File transfer 23 Telnet Remote login 25 SMTP 69 TFTP Trivial File Transfer Protocol 79 Finger Lookup info about a user 80 HTTP World Wide Web 110 POP-3 Remote access 119 NNTP USENET news
290
Penghantaran TCP Segmen TCP dihantar dalam datagram IP
Internet router hanya lihat pada kepala IP untuk majukan datagram TCP pada destinasi menterjemahkan segmen TCP
291
TCP dan penghantaran boleh-dipercayai
TCP guna banyak teknik yang (dibincangkan selepas ini) dalam kawalan ralat, aliran dan kesesakan untuk menyediakan penghantaran yang boleh dipercayai Guna ACK untuk penghantaran semula Masa-tamat Nombor jujukan untuk segmen Sliding window
292
Format Segmen TCP Kepala TCP segmen bermula dengan kepala format tetap 20 byte
293
‘Jabat-tangan tiga arah’ TCP
TCP menggunakan ‘jabat-tangan tiga arah’ ketika memulakan dan menamatkan hubungan untuk menyediakan kebolehpercayaan Tentukan kedua-dua nod bersedia dan selaraskan nombor jujukan rawak untuk sinkronikan hubungan
294
Memulakan Sambungan TCP
Guna segmen SYN untuk cipta satu sambungan Hos 1 hantar segmen SYN dan nombor jujukan rawak Hos 2 membalas segmen SYN, acknowledgment kepada Hos 1 dan nombor jujukan rawak Host 1 balas dengan acknowledgment
295
Menamatkan Sambungan TCP
TCP guna segmen FIN untuk menamatkan sambungan
296
Protokol Datagram Pengguna (User Datagram Protocol (UDP))
UDP merupakan protokol pengangkutan dalam set TCP/IP UDP menyediakan perkhidmatan datagram yang tidak dapat diharap/dipercayai sepenuhnya Paket mungkin hilang atau tidak menurut urutan Pengguna bertukar-tukar datagram, bukannya aliran data Berdasarkan tanpa-sambungan Tidak berpenimbal pada penghantar - UDP menerima data dari aplikasi dan terus menghantarnya Dupleks penuh - pindahan datagram boleh pada dua arah Digunakan apabila tiada kawalan ralat diperlukan
297
User Datagram Protocol
UDP hantar mesej tak-bersandaran dipanggil datagram di antara aplikasi atau proses pada hos komputer Penghantaran “Best effort'' – datagram boleh jadi hilang, dihantar tanpa turutan dsb. Checksum memastikan data integriti Titik hujung UDP dipanggil pengkalan/port
298
Well-known Port UDP Port Name Description 11 systat System statistics
53 domain DNS 69 tftp Trivial File Transfer Protocol (TFTP 161 snmp Simple Network Management Protocol (SNMP)
299
User Datagram Protocol (UDP)
UDP mempunyai ‘overhead’ yang rendah berbanding TCP Kepala UDP mudah : Nombor pangkalan Panjang mesej checksum
300
User Datagram Protocol (UDP)
UDP source port UDP destination port UDP message length UDP checksum Data
301
Kepala UDP
302
Ringkasan 2 protokol utama dalam lapisan pengangkutan TCP/IP :
TCP menyediakan aplikasi dengan perkhidmatan boleh-percaya, kawalan aliran, dupleks penuh dan berorientasikan sambungan UDP menyediakan aplikasi dengan perkhidmatan kurang dipercayai dan tanpa sambungan
303
Teknologi Rangkaian Komputer Senibina Internet dan Protokol TCP/IP
TK3133 Teknologi Rangkaian Komputer Antara Rangkaian : Senibina Internet dan Protokol TCP/IP
304
Pengenalan Antara Rangkaian : Konsep Senibina Protokol
305
Pengenalan Dalam dunia sebenar, komputer dihubungkan dengan pelbagai jenis teknologi LAN dan WAN Realitinya, rangkaian adalah heterogeneous iaitu rangkaian pelbagai jenis (dan bukan homogeneous) Mengandungi berjuta-juta rangkaian yang dihubungkan kepada tulang-belakang berkelajuan tinggi Mana-mana sistem perlu menyesuaikan dengan pelbagai teknologi Memperkenalkan konsep internetworking
306
Internetworking / Antara Rangkaian
Internetworking ialah skima untuk menyambungkan pelbagai rangkaian yang berlainan teknologi Menggunakan kedua-dua perkakasan dan perisian Perkakasan tambahan diletakkan di antara rangkaian Perisian berada pada komputer yang terhubung dengannya Sistem rangkaian yang bersambungan ini juga dipanggil internetwork / internet Juga dikenali sebagai rangkaian maya
307
AntaraRangkaian / Internetworking
Kenapa rangkaian berbeza? Rangkaian berbeza dengan protokol yang berbeza Install rangkaian sendiri Rangkaian berbeza guna teknologi berbeza Senario internetworking
308
Antara Rangkaian / Internetworking
309
Internet ialah koleksi sambungan pelbagai rangkaian
Koleksi Sub Rangkaian Internet ialah koleksi sambungan pelbagai rangkaian
310
Perbezaan Rangkaian
311
Sambungan Rangkaian Fizikal menggunakan Peranti Router
Router merupakan komponen atau peranti perkakasan yang digunakan untuk menyambungkan rangkaian Router mempunyai lebih antaramuka pada pelbagai rangkaian Router hantar dan serahkan paket di antara rangkaian-rangkaian Tukar paket jika perlu untuk memenuhi piawaian untuk setiap rangkaian yang berbeza teknologi (juga dipanggil sebagai gateway)
312
Router Contoh dua rangkaian fizikal disambungkan dengan satu router yang mengandungi 2 antaramuka berasingan untuk setiap sambungan rangkaian
313
Senibina Internet internetwork terdiri daripada pelbagai rangkaian yang dihubungkan oleh router (rangkaian boleh jadi LAN atau WAN)
314
Senibina Internet Router boleh mempunyai lebih daripada dua antaramuka
315
Internet The internet concept. (a) The illusion of a single network that TCP/IP software provides to users and applications, and (b) the underlying physical structure in which a computer attaches to one physical network, and routers interconnect the networks
316
Internet dilihat oleh TCP/IP
317
Protokol untuk Internet
TCP/IP merupakan protokol internetworking yang paling popular digunakan Protokol internetworking yang pertama Dibiayai oleh ARPA dan diambil alih oleh NSF Pelantar dan pengeluar tidak-bersandar
318
Lapisan TCP/IP Model OSI 7-lapisan tidak termasuk internetworking
Model Lapisan TCP/IP mengandungi lima lapisan
319
Lapisan TCP/IP dan Model OSI
320
Lapisan TCP/IP Lapisan 5: Aplikasi Lapisan 4: Pengangkutan
Menyamai lapisan 5,6 dan 7 dalam Model OSI Lapisan 4: Pengangkutan Menyamai lapisan 4 dalam Model OSI ; menyediakan penghantaran data boleh-percaya Lapisan 3: Internet Menakrifkan format seragam paket dihantar melalui rangkaian pada teknologi yang berbeza dan memberikan mekanisma untuk penghantaran paket oleh router
321
Lapisan TCP/IP Lapisan 2: Antaramuka Rangkaian
Menyamai lapisan 2 dalam Model OSI; takrifkan format kerangka Lapisan 1: Fizikal Menyamai lapisan 1 dalam Model OSI; takrifkan asas perkakasan rangkaian
322
Hos, Router dan Lapisan Protokol
Hos komputer ialah mana-mana sistem komputer yang terhubung pada internet yang melaksanakan aplikasi TCP/IP membenarkan pasangan hos pada internet berkomunikasi secara terus Kedua-dua hos dan router mempunyai/memerlukan timbunan TCP/IP Hos biasanya mempunyai satu antaramuka dan tidak majukan/forward paket Router majukan/hantar paket tetapi tidak memerlukan lapisan 4 dan 5
323
Lapisan Rangkaian Protokol Internet (IP)
Bagaimana mengendalikan rangkaian di dalam rangkaian ? Guna protokol lapisan rangkaian yang dipanggil sebagai Internet Protocol (IP) Membolehkan satu aturcara yang dilarikan pada satu komputer menghantar data kepada aturcara aplikasi yang dilarikan pada komputer lain pada rangkaian berjauhan
324
Protokol Internet (IP)
IP bertanggungjawab menyediakan penghantaran best-effort untuk paket (atau dikenali sebagai datagram dalam lapisan IP) Bagaimana komunikasi dalam Internet ? Lapisan pengangkutan ambil aliran data dan pecahkan kepada datagram Lapisan rangkaian hantar setiap datagram melalui Internet. Pemecahan kepada unit yang lebih kecil boleh berlaku sewaktu proses ini
325
Protokol Internet (IP) samb.
Pada destinasi , datagram akan dikumpulkan kembali oleh lapisan rangkaian kepada datagram asal dan dihantar kepada lapisan pengangkutan Best-effort tidak menjamin akan mengendalikan masalah tindanan datagram, lambatan atau penghantaran tidak-berjujukan, data rosak dan hilang Perkhidmatan yang ditawarkan oleh IP ialah tanpa-sambungan IP takrifkan format paket bebas-perkakasan yang boleh dihantar dipanggil Datagram IP
326
IP Datagram IPv4 takrifkan datagram maksimum 64Kb
Format kepala IP datagram
327
Kepala Protokol IPv4
328
Format IP Datagram Medan Penerangan VERSION Nombor versi IP datagram
IHLEN Berapa panjang kepala IP datagram TOS Jenis perkhidmatan yang ditawarkan Total Length Berapa panjang datagram
329
Protokol IP Medan Penerangan Identification
Pengenalan unik kepada datagram Fragment Offset Ofset bagi pecahan Time To Live Pembilang kepada bil maksima jangkahayat datagram Protocol Memberikan protokol pada lapisan atas mana Checksum Menakrifkan kesahihan kepala Source/destination address Alamat penuh nod sumber/destinasi Option Mungkin mengandungi option keselamatan
330
Pemecahan/Fragmentation
Setiap teknologi rangkaian takrifkan jumlah maksimum data yang boleh dihantar dalam satu paket. Batasan ini dikenali sebagai MTU (Maximum Transmission Unit) Apabila satu router terima satu datagram yang lebih besar dari MTU rangkaian dimana ia perlu dihantar, router akan pecahkan datagram kepada datagram lebih kecil dipanggil fragment (pecahan) Setiap fragment dihantar kepada destinasi yang kemudiannya bertanggungjawab memadan/menyambung kembali kepada datagram asal
331
Fragmentation Transparent fragmentation Nontransparent fragmentation
332
Fragmentation (2) Fragmentation when the elementary data size is 1 byte. (a) Original packet, containing 10 data bytes. (b) Fragments after passing through a network with maximum packet size of 8 payload bytes plus header. (c) Fragments after passing through a size 5 gateway.
333
Isu alamat Aspek utama dalam rangkaian maya ialah satu format alamat yang seragam Tidak boleh guna alamat perkakasan kerana teknologi berlainan menggunakan format alamat yang berbeza Format alamat mestilah tidak-bersandaran dengan mana-mana format alamat perkakasan yang tertentu Hos penghantar letakkan alamat internet destinasi dalam paket/datagram Router periksa alamat destinasi dan hantarkan paket pada destinasi
334
Alamat TCP/IP Pengalamatan dalam TCP/IP ditakrifkan oleh Internet Protocol (IP) Setiap hos diumpukkan dengan satu nombor 32-bit Dipanggil alamat IP atau alamat Internet Unik pada keseluruhan Internet Setiap datagram mengandungi alamat IP sumber dan destinasi
335
Alamat IP Setiap alamat IP dibahagikan kepada dua bahagian : no. rangkaian (prefix) dan no. hos (suffix) No. rangkaian menunjukkan rangkaian fizikal di mana komputer dihubungkan No. hos pula menunjukkan nombor unik komputer pada rangkaian Format alamat ini menjadikan routing lebih efisyen
336
Merekabentuk Alamat IP
Daripada 32-bit, beberapa bit diumpukkan pada prefix dan beberapa lagi bit pada suffix Prefix besar, suffix kecil - banyak rangkaian, sedikit hos pada rangkaian Prefix kecil, suffix besar - sedikit rangkaian, banyak hos pada rangkaian Oleh kerana adanya pelbagai jenis teknologi, perlu benarkan kedua-dua rangkaian besar dan kecil
337
Pengkelasan Alamat Pelbagai format alamat untuk benarkan kedua-dua prefix besar dan kecil Setiap format dipanggil satu kelas alamat Sesuatu kelas alamat dikenalpasti melalui empat bit yang pertama
338
Format Kelas Alamat IP
339
Alamat IP Khas
340
Menggunakan kelas alamat IP
Kelas A, B dan C adalah kelas primari Digunakan untuk pengalamatan hos yang biasa Kelas D untuk tujuan multicast, satu bentuk terhad broadcast/terpancar Kelas E dikhaskan untuk tujuan masa depan
341
Dotted Decimal Notation
Nombor IP adalah dalam nombor binari 32-bit. Untuk memudahkan manusia, notasi dotted decimal digunakan Nombor 32-bit diungkapkan sebagai 4 seksyen 8-bit dalam nombor decimal dan guna titik/noktah untuk memisahkan seksyen Untuk mengenalpasti kelas dari nombor decimal, boleh guna julat alamat
342
Dotted Decimal Notation
343
Dotted Decimal Notation
344
Julat Kelas daripada Alamat IP
345
Bilangan Rangkaian dan Hos
346
Contoh Pengalamatan kelas
Contoh pegumpukan alamat IP pada hos
347
Subnet Membolehkan rangkaian dipecahkan kepada beberapa sub rangkaian
Contoh : satu tapak mengandungi satu alamat IP kelas B diumpukkan pada rangkaian tetapi mempunyai dua atau lebih rangkaian fizikal. Hanya router setempat tahu tentang pelbagai subrangkaian dan bagaimana nak hantar data padanya, router lain hanya tahu ada satu rangkaian sahaja
348
Satu rangkaian kampus mengandungi LAN untuk pelbagai jabatan
Subnet Satu rangkaian kampus mengandungi LAN untuk pelbagai jabatan
349
Satu rangkaian Kelas B disubnetkan
Memerlukan maklumat tambahan yang mengkhususkan batas di antara prefiks dan suffiks dipanggil subnet mask Satu rangkaian Kelas B disubnetkan kepada 64 subnet
350
IPv6 128 bit bit alamat Kepala lebih mudah Lebih sokongan perkhidmatan
keselamatan
351
Kepala IPv6
352
Protokol Kawalan Internet
Sebagai tambahan kepada IP, lapisan Rangkaian Internet mempunyai beberapa protokol kawalan pada lapisan rangkaian/internet Protokol Resolusi Alamat (Address Resolution Protocol (ARP)) Protokol Songsangan Resolusi Alamat (Reverse Address Resolution Protocol (RARP)) Protokol Utusan Kawalan Internet (Internet Control Message Protocol (ICMP)) Protokol Pengurusan Kumpulan Internet (Internet Group Management Protocol (IGMP))
353
Protokol Resolusi Alamat (Address Resolution Protocol (ARP))
Hubungan antara hos menggunakan alamat IP, tetapi hubungan lapisan pautan data menggunakan alamat MAC protokol ini digunakan untuk mencari alamat MAC bagi NIC yang digunakan oleh hos yang menggunakan IP tertentu Hantar permintaan secara broadcast hos yang mempunyai IP akan menjawab
354
Protokol Resolusi Alamat (Address Resolution Protocol (ARP))
355
Protokol Sonsangan Resolusi Alamat (Reverse ARP)
Biasanya digunakan oleh komputer tanpacakera. Pada masa di boot, diketahui alamat MAC, ingin diketahui alamat IP nya. Hanya boleh dibuat dalam segmen yang sama.
356
Protokol Utusan Kawalan Internet (Internet Control Message Protocol (ICMP))
Digunakan untuk konfigurasi dan menjalankan rangkaian IP (oleh kerana IP tidak boleh dipercayai) Dapat memberi maklum balas tentang masalah rangkaian Jenis utusan destinasi tidak dapat dicapai masa hidup dilampaui (kiraan TTL mencapai 0) masalah parameter (header tidak dikenali)
357
Protokol Utusan Kawalan Internet (Internet Control Message Protocol (ICMP))
mengarahkan ke tempat lain membalas permintaan/sambutan (paket ping) membalas permintaan/sambutan dengan maklumat masa (ping yang perlukan maklumat masa (timestamped) menggunakan IP, jadi ia sendiri tidak boleh diyakini sampai Contoh arahan yang menggunakan ICMP Ping dan Traceroute
358
Protokol Utusan Kawalan Internet (Internet Control Message Protocol (ICMP))
359
Internet Group Management Protocol (IGMP)
Untuk terlibat dalam IP multicast pada rangkaian tempatan dan pelbagai rangkaian lain, hos dan multicast router mestilah mempunyai perisian yang membenarkannya hantar dan terima multicast datagram. Mesti guna Internet Group Management Protocol untuk komunikasi maklumat ahli kumpulan Hampir sama dengan ICMP – guna IP datagram dan bertukar mesej
360
IGMP Secara konsepnya ada dua fasa :
Fasa 1 : apabila satu hos sertai satu kumpulan multicast, ia akan hantar satu IGMP mesej kepada alamat kumpulan multicast mengistiharkan keahliannya. Multicast router tempatan terima mesej dan maklumkan maklumat ahli kumpulan ke multicast router lain dalam internet
361
IGMP Fasa 2 : oleh kerana keahlian adalah dinamik, multicast router secara berkala mestilah membuat undi untuk hos pada rangkaian setempat untuk memastikan samada mana-mana hos masih menjadi ahli (aktif atau tidak). Jika aktif, maklumkan pada multicast router yang lain.
362
Ringkasan Internet ialah koleksi rangkaian fizikal yang disambungkan menjadi satu rangkaian maya Router menyediakan sambungan fizikal dan majukan paket diantara rangkaian Hos berkomunikasi melalui pelbagai rangkaian melalui paket yang dimajukan oleh router TCP/IP ialah protokol internetworking yang paling popular digunakan
363
Ringkasan Rangkaian maya perlu skima pengalamatan yang seragam, tidak bersandar pada perkakasan IP takrifkan pengalamatan internet Protokol tambahan dalam lapisan Internet lain ialah ARP, RARP, ICMP dan IGMP
364
Teknologi Rangkaian Komputer Teknologi Rangkaian Kawasan Luas (WAN)
TK3133 Teknologi Rangkaian Komputer Teknologi Rangkaian Kawasan Luas (WAN)
365
Pengenalan Keperluan untuk meliputi jarak lebih jauh
Pekerja syarikat perlu capai rangkaian mereka ketika di luar pejabat Menghubungkan cawangan-cawangan organisasi Berkongsi maklumat dengan organisasi lain yang terpisah jauh oleh jarak Badan kerajaan, swasta, pendididikan dan individu perlu capaian kepada maklumat yang ada pada Internet Teknologi ini dipanggil WAN - Wide Area Network (Rangkaian Kawasan Luas)
366
WAN Memerlukan satu set teknologi dan peraturan implementasi yang berbeza dari LAN. membincangkan konsep rangkaian pada jarak jauh dan teknologi yang biasa digunakan untuk menyambungkan komputer yang berada di lokasi berbeza (negeri, negara & benua)
367
Jenis pensuisan rangkaian
Data boleh dihantar ke destinasi yang jauh melalui pelbagai jenis talian, menggunakan salah satu daripada dua jenis ini Pensuisan litar (circuit switching) Pensuisan paket (packet switching)
368
Pensuisan litar Teknologi lama sesuai untuk penghantaran data masa-nyata (seperti percakapan telefon) Pensuisan litar ialah kaedah yang digunakan sama bagi membuat sambungan telefon (litar fizikal dikhaskan) Sambungan fizikal perlu dibina antara dua stesen sebelum penghantaran data dapat dilakukan Berjenis orientasi-sambungan (connection oriented) kerana ada satu sambungan dibina sebelum penghantaran dimulakan
369
Pensuisan paket Data dipecahkan kepada beberapa unit yang lebih kecil dipanggil paket dan dihantar dari satu hos ke hos yang lain dengan boleh mengikut laluan yang berbeza (walaupun tiada laluan terus) untuk sampai kepada destinasi dan kemudiannya digabungkan kembali pada penghujungnya
370
Pensuisan (a) Pensuisan Litar (b) Pensuisan Paket
371
Pensuisan Pensuisan Litar (b) Pensuisan Mesej (c) Pensuisan Paket
372
Perbandingan Rangkaian Pensuisan
373
Pensuisan paket Dua pendekatan dalam menghantar data melalui pensuisan paket :- Datagram (tanpa sambungan) Pastikan setiap paket mengandungi maklumat mencukupi untuk membolehkan mana-mana suis menghantar kepada destinasi Litar Maya (berorientasikan sambungan) Memerlukan pembinaan sambungan maya daripada hos sumber ke destinasi Samada Litar Maya Bersuis atau Litar Maya kekal
374
Perbandingan Litar Maya & Datagram
375
Contoh Sistem Komunikasi WAN
Cth WAN : Sistem Telefon PSTN ISDN xDSL Arpanet X.25 Frame Relay ATM
376
PSTN PSTN – Public Switched Telephone Network
Asalnya untuk menghantar suara rangkaian telefon dial-up awam biasa guna Sedia ada di seluruh dunia murah Sambungan pelbagai pusat pensuisan dan sambungan kepada pelanggan Jenis rangkaian pensuisan litar
377
Dail-up dan leased line
2 cara : guna dial-up dan leased line (talian pajak) Modem digunakan pada infrastruktur telefon yang telah sedia ada untuk sambungan dail-up (sambungan sementara sepanjang sessi) Untuk leased line, sambungan tetap berkelajuan tinggi tanpa melibatkan mendail khas dari satu titik kepada titik yang lain (contoh dari pejabat ke ISP)
378
ISDN ISDN – Integrated Services Digital Network Pembaikan daripada IDN
Menyokong suara, data dan video menggunakan penghantaran medium digital melalui satu talian lebarjalur tinggi Kombinasi teknik pensuisan litar dan paket
379
ISDN Perkhidmatan asas (basic) ialah 2B + D (BRI)
di mana B = satu saluran data 64kbps D = satu saluran sekunder (pengisyaratan) 16kbps ISDN Primary Access - 23B+D (64kbps) (PRI) B-ISDN – Broadband ISDN Lebih lebarjalur dari ISDN Guna fiber optik dan lebarjalur 600Mbps
380
Teknologi Pensuisan Litar yang lain
xDSL – Digital Subscriber Line Koleksi teknologi untuk hantar data pada kelajuan tinggi melalui talian biasa Cth : ASDL (Asymmetric DSL) untuk mengoptimakan pengguna yang terima banyak maklumat berbanding dengan yang dihantar (high-bit downstream dan low-bit upstream) Kelajuan antara 16 – 640 kbps (upstream) dan Mbps hingga 6 Mbps downstream
381
Teknologi Pensuisan Litar yang lain
DSL SDSL (Symmetric DSL) Simetrik kadar bit pada kedua-dua hala HDSL (High Data Rate DSL) Kadar bit Mbps kedua-dua arah VDSL (Very HDSL) Kadar bit dari Mbps hingga 55.2 Mbps tetapi untuk jarak dekat dan perlu Optical Network Unit (ONU)
382
Teknologi Pensuisan Paket
ARPANET dibangunkan oleh ARPA untuk Jabatan Pertahanan USA merupakan WAN pertama menggunakan pensuisan paket membentuk Internet seperti kini
383
Pensuisan paket X.25 Rangkaian pensuisan paket komersial yang pertama dengan rujukan CCITT X.25 – sebenarnya satu protokol piawai bagaimana WAN berkomunikasi menggunakan X.25 suis paket yang dihubungkan oleh talian pajak Menyediakan antaramuka antara satu DTE (hos) dan DCE (suis rangkaian) Berkongsi talian melalui multipleksan Satu sambungan di antara penghantar dan penerima dipanggil litar maya (atau sambungan logikal) Lambat dan pengurusan tinggi serta kelambatan panjang
384
Senibina Lazim bagi X.25
385
Perbezaan di antara Protokol X.25 dan TCP/IP
Messages have boundaries Messages have no boundaries Urgent data may overtake ordinary data in the data streams With TCP, urgent data cannot preceed ordinary data that has been sent The X.25 packet layer depends upon the datalink level for reliable delivery of data TCP/IP requires very little reliance on the lower layers X.25 protects data against errors on the data link by CRC code TCP protects data against errors with checksum X.25's CRCs are computed separately for each transmission link, hence protection is end-to-end TCP's checksums are computed once by the sender and checked once by the receiver, hence protection is not end-to-end The packet layer depends on the data link layer to tell it when delivery is not possible TCP/IP retransmit data if acknowledge-ment is not received. If this happens after a certain number of times, it decides that the network's reliability is too poor to continue data transmission The maximum number of virtual circuits that can be "open" at any time is limited by the amount of free buffer memory on the X.25 interface In contrast, TCP's buffering is taken from a pool on the host, hence there is no limit on the number of open connections
386
Frame Relay Teknologi pensuisan paket baru (fast-packet) berkelajuan tinggi digunakan pada talian digital untuk blok data yang besar yang berubah-ubah saiznya Pembaikan daripada X.25 – perlaksanaan tinggi, kebolehpercayaan tinggi, kos-effektif Guna PVC (berorientasikan sambungan)
387
ATM Asynchronous Transfer Mode (ATM)
Sama seperti pensuisan paket rangkaian tetapi paling popular Menyokong aplikasi berkelajuan tinggi (data, streaming audio dan video) Kadar data 25Mbps, 155Mbps, 622Mbps, 1Gbps Pecahkan data kepada pecahan lebih kecil (sel) yang tetap saiznya iaitu 53 byte (48 byte data dan 5 byte overhead)
388
ATM Berjenis berorientasikan sambungan
Sambungan di antara dua titik dipanggil litar maya (VC) – (samada PVC atau SVC) Guna pre-defined circuit
389
Rangkaian Wayarles Contoh rangkaian selular menggunakan GSM (Global System for Mobiles) untuk hantar mobil suara dan perkhidmatan data digital Teknologi GSM : 2G GPRS 3G
390
Ringkasan Pelbagai teknologi WAN dari dua jenis : Pensuisan litar
PSTN, ISDN, DSL Pensuisan Paket Arpanet, X.25, Frame Relay dan ATM
391
Teknologi Rangkaian Komputer
TK3133 Teknologi Rangkaian Komputer Laluan dalam WAN
392
Pengenalan Untuk menghubungkan komputer jarak jauh, rangkaian perlu guna suis paket menghubungkan medium Suis Paket (Packet Switches) juga dikenali sebagai router Setiap suis bawa keseluruhan paket dari satu sambungan kepada satu sambungan yang lain Satu komputer khas dengan antaramuka rangkaian, ingatan dan aturcara digunakan sebagai memproses paket
393
Sambungan pada router Router dihubungkan dengan komputer dan router yang lain
394
Sambungan pada router Router boleh dihubungkan bersama-sama membentuk WAN Setiap router boleh dihubungkan dengan satu atau lebih suis dan satu atau lebih komputer
395
Sambungan pada router Cth : Sambungan 4 router dan 8 komputer membentuk WAN
396
Simpan dan Hantar (Store and Forward)
WAN membenarkan banyak komputer menghantar paket serentak Asas prinsip dalam sistem pensuisan paket kawasan luas ialah simpan dan hantar Perlukan penimbal untuk simpan paket yang tiba, proses paket untuk tentukan output antaramuka untuk dihantar dan hantar paket
397
Pengalamatan dalam WAN
Hampir sama seperti LAN Data dihantar dalam paket (sama spt. kerangka) Setiap paket mempunyai format beserta kepala Kepala paket termasuk alamat destinasi dan sumber
398
Maklumat Pada Router Router mesti memilih sambungan keluar untuk penghantaran serahan (samada local/tempatan atau router lain (next-hop) Pilihan adalah berdasarkan alamat destinasi pada paket Maklumat pada router (jadual) hanya mengandungi maklumat next-hop Jadi, pada setiap paket, router lihat destinasi pada jadual dan hantar melalui sambungan hop seterusnya Proses penghantar seterusnya dipanggil ‘routing/laluan’ Maklumat disimpan dalam jadual laluan (routing table)
399
Teknik Penentuan Laluan
Untuk menentukan laluan suatu hos atau router memerlukan routing table Satu teknik utk mengurangkan kandungan routing table ialah next-hop routing
400
Figure 19.28 Next-hop routing
401
Figure 19.29 Network-specific routing
402
Penentuan Laluan Strategi
Tepat : paket sampai dengan selamat ke tempat tuju Mudah : mudah dilaksanakan dan dikemaskini Lasak : kegagalan dalam rangkaian masih membenarkan komunikasi Stabil : perubahan yang kecil dalam penambahan hubungan tidak menjejaskan keseluruhan laluan Adil : setiap hos mempunyai peluang yang sama Optimum : menggunakan kesemua jejak dan lebarjalur yang dipunyai
403
Penentuan laluan 2 jenis Statik Dinamik
Laluan dikira lebih awal dan tidak berubah Shortest Path Routing Lambakan (Flooding) Dinamik Pemilihan laluan berubah bergantung kepada situasi rangkaian Distance vector routing Link state routing
404
Shortest Path Routing Algoritma statik
cari “jarak terpendek” dalam laluan dari hos sumber kepada hos destinasi Algoritma popular untuk mengira ialah Dijkstra Algorithm guna perwakilan graf
405
Figure 21.12 Example of an internet
Contoh suatu antara rangkaian (internetwork) kecil yg terdiri drp 7 rangkaian (N1, N2, .. N5) + 2 rangkaian titik-ke-titik A, B, .., F merupakan router
406
Figure 21.13 Graphical representation of an internet
407
Dijkstra Algorithm 1. Start with the local node (router): the root of the tree. 2. Assign a cost of 0 to this node and make it the first permanent node. 3. Examine each neighbor node of the node that was the last permanent node. 4. Assign a cumulative cost to each node and make it tentative. 5. Among the list of tentative nodes Find the node with the smallest cumulative cost and make it permanent. 2. If a node can be reached from more than one direction 1. Select the direction with the shortest cumulative cost. 6. Repeat steps 3 to 5 until every node becomes permanent.
408
Setiap router menggunakan algoritma Dijkstra untuk mengira laluan terpendek di antara 2 titik dlm rangkaian
409
Figure 21.20 Shortest-path calculation for Router A
410
Table 21.2 Link state routing table for router A
Network Cost Next Router Other Information N1 5 C N2 7 D N3 10 B N4 11 N5 15
411
Shortest Path Routing Kira laluan terpendek di antara dua nod
Setiap nod dilabelkan dengan jaraknya dari nod sumber di sepanjang laluan terbaiknya yang diketahui
412
Lambakan Setiap paket akan dihantar kepada semua nod yang berhampiran kecuali nod penghantar Masalah bila berlaku tindanan Cara atasi Kira nod Jejak paket Selective flooding – pilih hanya laluan yang sedang menuju kepada arah yang betul
413
Distance Vector Routing
Algorithma penentuan laluan dinamik Juga dikenali sebagai Bellman-Ford routing atau Ford-Fulkerson algorithm Digunakan di Internet Setiap router menyelenggara jadual laluan dari semasa ke semasa Setiap router akan memberi jadual laluannya kepada jiran pada masa tertentu 2 bahagian – laluan keluar yang dipilih dan jarak destinasi
414
Distance Vector Routing
(a) A subnet. (b) Input from A, I, H, K, and the new routing table for J.
415
Link State Routing Juga dikenali sebagai Shortest Path First (SPF) routing Router hantar mesej melalui rangkaian dengan membawa status talian antara dua router, dan mesej tersebut dipancar kepada semua router Setiap router terima mesej status dan gunakannya untuk bina graf rangkaian Router kemudiannya guna Dijkstra algorithm untuk menghasilkan jadual laluan dengan dirinya sendiri sebagai sumber
416
Link State Routing Satu subnet
Keadaan/status sambungan paket untuk subnet
417
Ringkasan WAN guna router dan sambungan titik-ke-titik
Router hantar paket ke destinasi guna jadual laluan dan strategi penentuan laluan
418
Teknologi Rangkaian Komputer
TK3133 Teknologi Rangkaian Komputer Teknologi LAN (1)
419
Pengenalan Konsep rangkaian kawasan setempat (LAN) dan teknologinya
Kepentingan perkongsian dalam LAN Asas topologi rangkaian Pengalamatan perkakasan dan pengecaman jenis kerangka
420
Kategori Rangkaian Jenis sambungan rangkaian:
Titik-ke-titik atau Rangkaian Mesh Perkongsian Saluran Komunikasi
421
Komunikasi Titik-ke-Titik
Konfigurasi talian asal sistem komunikasi Komputer dihubungkan oleh saluran komunikasi yang setiap satunya menghubungkan dua komputer membentuk rangkaian mesh atau titik-ke-titik membenarkan fleksibiliti dalam komunikasi perkakasan, format paket dan sebagainya membekalkan keselamatan oleh kerana saluran komunikasi tidak dikongsi
422
Sambungan dalam titik-ke-titik
Bilangan wayar bertambah apabila bilangan komputer turut bertambah Cth : sambungan 2,3,4 komputer
423
Sambungan dalam titik-ke-titik
menambah satu komputer (komputer ke-N) memerlukan N-1 sambungan baru Bil. sambungan = (N2 – N)/2 Kelemahannya mahal dan talian terlalu banyak
424
Perkongsian Saluran Komunikasi
Berbeza dengan rangkaian jarak jauh Mengatasi kelemahan titik-ke-titik yang mahal, berdedikasi dan tindanan Memperkenalkan LAN – Rangkaian Kawasan Setempat yang berkongsi satu saluran komunikasi (kabel) oleh beberapa komputer
425
Rangkaian Kawasan Setempat
Mengurangkan bilangan saluran komunikasi dengan memperkenalkan Rangkaian Kawasan Setempat (LAN) LAN dibangunkan pada awal 1970an Idea utama - mengurangkan bilangan saluran dengan berkongsi sambungan di antara komputer Tetapi tidak sesuai untuk jarak jauh kerana masalah koordinasi
426
Rangkaian Kawasan Setempat
Teknologi LAN mengurangkan kos dengan mengurangkan bilangan sambungan Tetapi komputer yang terhubung terpaksa bersaing untuk menggunakan sambungan yang dikongsi menggunakan prinsip locality of reference untuk dapatkan corak komputer berkomunikasi
427
Rangkaian Terpancar LAN adalah rangkaian terpancar
paket data yang dihantar oleh satu stesen akan dihantar kepada kesemua stesen Pengenalan topologi dalam LAN rangkaian boleh dikategorikan mengikut bentuk 3 topologi yang popular bintang, cincin dan bas
428
Topologi Bintang Semua komputer dihubungkan kepada satu titik tengah dipanggil hub Hub sebagai peranti yang terima paket data dan hantar kepada destinasi
429
Topologi Bintang Secara praktiknya, pemasangan kabel boleh selari (atau tidak) dengan komputer
430
Topologi Bintang Akibatnya :-
431
Topologi Cincin Komputer dihubungkan dalam satu gelung tertutup
Hos pertama akan hantar data kepada kedua, kedua hantar data kepada ketiga dan seterusnya. Kabel penyambung yang pendek dari komputer kepada cincin
432
Topologi Cincin Satu komputer menghubungkan dua komputer
433
Topologi Bas Satu kabel menghubungkan semua komputer
Setiap komputer mempunyai penyambung kepada kabel yang dikongsi Komputer mesti sinkroni dan benarkan hanya satu komputer menghantar data pada satu masa
434
Topologi Bas Satu kabel menghubungkan banyak komputer
435
Pelbagai Topologi Topologi masing-masing mempunyai kebaikan dan kelemahannya Pilihan bergantung kepada skema pendawaian
436
Contoh Rangkaian Kawasan Setempat Bas - Ethernet
Ethernet ialah kawalan capaian rangkaian LAN yang paling biasa digunakan Dibangunkan oleh Xerox pada pertengahan 70an - diurus oleh IEEE Menggunakan topologi bas satu kabel sepaksi (ether) sambung pelbagai komputer
437
Rangkaian Kawasan Setempat - Ethernet
Satu kabel Ethernet dipanggil segmen had sehingga 500m panjangnya Kadar penghantaran data ialah 10Mbps, 100Mbps (Fast Ethernet) dan 1Gbps (Gigabit Ethernet) Menggunakan pemodulatan isyarat Pengenkodan Manchester
438
Pengenkodan Manchester
(a) Binary encoding, (b) Manchester encoding, (c) Differential Manchester encoding.
439
Rangkaian Kawasan Setempat - Operasi Ethernet
Satu komputer hantar pada satu masa isyarat ialah pembawa yang dimodulasikan yang dibawa daripada penghantar pada dua arah sepanjang segmen
440
Carrier Sense Multiple Access with Collision Detection CSMA/CD
Tidak ada kawalan pusat yang uruskan apabila komputer hantar pada ether guna CSMA untuk koordinasi penghantaran di antara komputer yang terhubung Carrier sense: stesen mendengar saluran sebelum hantar Collision Detection: stesen boleh tentukan samada kerangka mengalami pertembungan dengan mendengar saluran ketika menghantar
441
CSMA/CD - IEEE 802.3 Piawaian 802.3
Asas ialah 10-Mbps “Ethernet”
442
LAN Tanpa Wayar 802.11 dan CSMA/CA
Beroperasi pada 11Mbps menggunakan frekuensi dalam julat 2.4 GHz Mengelakkan pertembungan guna CSMA dengan Collision Avoidance
443
LocalTalk Teknologi LAN yang guna topologi bas
antaramuka termasuk komputer Macintosh kos-rendah, senang untuk pemasangan dan penyambungan guna CSMA/CD
444
Bas Token - IEEE 802.4 Kelemahan bas sebab ada pertembungan – Pilih teknik elak pertembungan Konsep Token – bas dan ring Hanya penghantar yang terima token dibenarkan menghantar kerangka Lepas giliran hantar, passkan token
445
Bas Token Tetapkan giliran siapa selepas ini untuk terima token untuk keadilan capaian
446
Cincin Token - IEEE 802.5 (IBM Token Ring)
Beroperasi pada 4 dan 16 Mbps Tiada bas hanya nod dan talian guna penghantaran token untuk sinkronikan capaian pada cincin Setiap nod hantar kerangka mengikut pusingan jam dengan mendapatkan token terlebih dahulu
447
FDDI Fiber Distributed Data Interconnect (FDDI) adalah teknologi cincin guna fiber optik di antara stesen hantar pada kadar 100Mbps guna sepasang fiber untuk membentuk 2 gelung sepusat untuk tujuan back-up jika berlaku kerosakan
448
FDDI Penggunaan dua arah aliran
449
ATM - Rangkaian Bintang
Teknologi Asynchronous Transfer Mode mengandungi suis paket di mana komputer boleh dihubungkan Suis ATM membentuk hub di mana komputer dihubungkan dalam topologi bintang data daripada penghantar dilalukan terus melalui suis kepada destinasi
450
ATM - Rangkaian Bintang
Kadar penghantaran melebihi 100Mbps menggunakan fiber optik untuk sambungkan komputer kepada suis setiap sambungan mengandungi 2 fiber
451
Komunikasi Pasangan Komputer dalam LAN
Teknik bagaimana menghantar mesej melalui medium LAN kepada satu destinasi komputer yang khusus Penghantar komputer menggunakan alamat perkakasan untuk mengenalpasti destinasi yang dituju dalam kerangka Penghantar turut kenalpasti jenis data yang dibawa di dalam kerangka
452
Mengenal destinasi Data dihantar pada rangkaian yang dikongsi sampai pada semua komputer yang dihubungkan kepadanya perantaramuka perkakasan kesan penghantaran kerangka dan ekstrak kerangka daripada medium Tapi kebanyakan aplikasi hanya mahu data dihantar kepada destinasi sahaja dan bukannya semua komputer
453
Pengalamatan Perkakasan
Kebanyakan teknologi rangkaian mempunyai satu skima pengalamatan perkakasan yang mengenalpasti sesuatu stesyen atau komputer Setiap stesen diumpukkan satu alamat perkakasan numerik atau alamat fizikal yang unik Penghantar akan masukkan alamat perkakasan pada setiap kerangka yang dihantar (sumber dan destinasi) Hanya stesyen yang dikenal dari kerangka terima salinan kerangka tersebut
454
Perkakasan LAN dan penapisan paket
Organisasi perkakasan LAN dan komputer
455
Format Alamat Perkakasan
Nilai numerik saiz dipilih dari teknologi rangkaian tertentu Panjangnya dari satu sehingga enam bytes unik dalam satu LAN statik, dinamik dan boleh-konfigur
456
Format Kerangka dan Kepala Kerangka
Piawaian Teknologi LAN takrifkan format kerangka untuk setiap teknologi format am: Kepala mempunyai alamat dan maklumat tambahan (dalam medan saiz tetap) kawasan data boleh pelbagai saiz
457
Contoh Format Kerangka
Format Kerangka Ethernet
458
Ringkasan Teknologi LAN menggunakan medium komunikasi yang dikongsi untuk menyambungkan pelbagai komputer pada jarak yang dekat perlu sinkronikan penggunaan medium untuk perkongsian muatan Topologi LAN - bintang, cincin, bas Teknologi LAN - Ethernet, LocalTalk, FDDI, ATM, tanpa wayar
459
Ringkasan Teknologi LAN menggunakan alamat perkakasan untuk kenalpasti destinasi untuk kerangka yang dihantar pada saluran komunikasi yang dikongsi Setiap teknologi LAN takrifkan format perkakasan Alamat boleh jadi umpukan statik, dinamik dan boleh-konfigur Kerangka termasuk kepala yang terkandung alamat destinasi, sumber dan maklumat lain serta kawasan data
460
Teknologi Rangkaian Komputer
TK3133 Teknologi Rangkaian Komputer Teknologi LAN (2)
461
Pengenalan Kad Antaramuka Skima Pendawaian LAN
kenapa perlu kad yang berasingan apakah dia ‘transceiver’? Skima Pendawaian LAN Topologi logikal dan fizikal Bagaimana boleh meluaskan LAN?
462
Kelajuan LAN dan komputer
Kelajuan penghantaran data LAN adalah sangat pantas berbanding kelajuan CPU Kelajuan LAN tidak bergantung kepada mana-mana kelajuan pemproses membenarkan campuran sistem padanya komputer baru boleh disambung tanpa mempengaruhi kelajuan LAN
463
Perkakasan Antaramuka Rangkaian
Komputer guna perkakasan khas untuk sambungan rangkaian kad antaramuka rangkaian (NIC) yang memahami isyarat elektrik digunakan pada rangkaian, kadar di mana data diterima dan dihantar serta perincian kerangka penyambung pada belakang komputer terima kabel kepada rangkaian fizikal
464
NIC dan perkakasan Rangkaian
NIC dibina hanya untuk satu jenis rangkaian fizikal antaramuka Ethernet tak boleh guna dengan Token Ring Walaubagaimanapun, sesetengah NIC boleh digunakan dengan perkakasan lain yang bersamaan thick, thin dan 10BaseT Ethernet 10Mbps dan 100Mbps Ethernet
465
Sambungan antara NIC dan rangkaian fizikal
2 cara :- NIC terus sambung kepada medium Kabel dari NIC sambung kepada tambahan litar yang bersambung dengan medium Cara Pendawaian Ethernet Piawaian 10Base5 Piawaian 10Base2 Piawaian 10BaseT
466
Sambungan antara NIC dan rangkaian fizikal
467
10Base5 - Thick Ethernet Guna kabel sepaksi
kabel AUI (drop cable) dari NIC kepada transceiver Kabel AUI bawa isyarat digital dari NIC kepada transceiver Transceiver janakan signal analog pada kabel sepaksi
468
10Base5 - Thick Ethernet Satu kabel AUI menyambung komputer kepada transceiver
469
10Base5
470
10Base5 Transceiver
471
Segmen Ethernet
472
10Base2 - Thin Ethernet Guna kabel sepaksi yang lebih nipis/kurus - lebih murah dan senang dipasang daripada Thick-net coax Transceiver dibina pada NIC - terus sambung kepada medium kabel sepaksi guna BNC connector
473
10Base2
474
10Base2 - Thin-Net
475
10Base-T 10Base-T (Twisted pair/ TP Ethernet)
gantikan kabel AUI dengan kabel pasangan terpiuh gantikan thick coax dengan hub
476
10BaseT
477
Kategori Kabel UTP
478
Ethernet Semua teknologi pendawaian guna spesifikasi Ethernet yang sama format kerangka sama algorithma CSMA/CD yang sama NIC boleh terima semua ketiga-tiga teknologi sambungan
479
Perbandingan skima pendawaian
480
Topologi dan Teknologi Rangkaian
10Base-T logikalnya topologi bas; tetapi pendawaian fizikal ialah bintang Juga dikenali sebagai star-bus Ethernet
481
Ethernet Berkelajuan Tinggi
482
Fast Ethernet Pengkabelan Fast Ethernet
483
Gigabit Ethernet Kadar data 1000 Mbps atau 1 Gbps
Dikenali sebagai 1000BaseSX/LX atau 1000BaseT Guna suis Menggunakan fiber optik Bertindak sebagai tulang belakang rangkaian untuk hubungkan LAN dan LAN kelajuan tinggi
484
Perluasan LAN Teknologi LAN direkabentuk dengan kekangan kelajuan, jarak dan kos Teknologi LAN biasanya boleh merangkumi, paling jauh beberapa ratus meter Bagaimana boleh meluaskan LAN?
485
Merekabentuk LAN untuk jarak
Kebanyakan LAN menggunakan medium yang dikongsi - Ethernet, token ring Panjang medium mempengaruhi keadilan, berkongsi capaian kepada medium CSMA/CD – kelambatan di antara kerangka, minimum panjang kerangka Penghantaran Token – masa mengelilingi untuk token Panjang medium mempengaruhi kekuatan isyarat elektrik dan imunisasi hingar
486
Perluasan LAN Beberapa teknik meluaskan lingkungan diameter medium LAN
Kebanyakkannya menggunakan tambahan perkakasan Isyarat LAN dibawa di antara segmen LAN Hasilnya teknologi yang bercampur-campur tetapi tetap dengan kekangan kejuruteraan asal sementara memperluaskan jarak
487
Repeater (Pengulang) Untuk memanjangkan medium LAN
Kekuatan isyarat mempengaruhi had panjang Untuk atasinya guna Repeater – dua-arah, amplifier (penguat) analog yang menghantar semula isyarat analog
488
Repeater Satu repeater secara efektifnya mengandakan panjang satu segmen LAN
489
Ethernet repeater Hanya salin isyarat di antara segmen
Tidak memahami format kerangka Tidak mengandungi alamat perkakasan Mana-mana segmen Ethernet terhad kepada 500 meter Repeater boleh gandakan kepada 1,000 meter
490
Had Ethernet Repeater Piawaian Ethernet termasuk menghadkan 4 repeater di antara mana-mana dua stesen Ethernet
491
Kelebihan dan Kelemahan Repeater
Mudah untuk digunakan – terus plug-in Repeater hanya hantar-semula isyarat analog Pertembungan mempengaruhi keseluruhan rangkaian Hingar juga turut di bawa sepanjang rangkaian
492
Bridge (Jambatan) Juga hubungkan dua segmen LAN
Menghantar-semula kerangka daripada satu segmen ke segmen yang lain Menguruskan keseluruhan kerangka Menggunakan NIC seperti stesen yang lain Laksanakan pemprosesan pada kerangka
493
Bridge Penggunaan bridge dalam menyambungkan dua segmen LAN
494
Kelebihan Bridge Sangat mudah untuk digunakan – hanya plug-in
Asingkan pertembungan, hingar Lakukan penapisan kerangka Hanya hantar kerangka bila perlu sahaja pada segmen LAN kepada destinasi Hantar paket multicast dan broadcast Guna jadual
495
Bagaimana bridge bina jadual
Bridge periksa alamat sumber pada setiap kerangka Tambah kemasukkan kepada senarai untuk segmen LAN daripada mana kerangka tersebut diterima Mesti hantar mana-mana kerangka yang destinasinya tidak ada dalam senarai ke setiap antaramuka bridge
496
Jadual Bridge
497
Bridge Boleh guna banyak bridge untuk sambungkan LAN segmen
Kelemahan mengakibatkan gelung – atasinya dengan algorithma Distributed Spanning Tree
498
Bridge di antara bangunan
Bridge berada pada satu bangunan dengan penyambung yang panjang kepada segmen LAN di bangunan yang lain
499
Bridge jarak jauh Boleh guna talian pajak, gelombang mikro, laser atau satelit untuk sambungkan dua bridge dan segmen LAN
500
Pensuisan Bagi setiap port/pengkalan untuk pisahkan satu LAN segmen
Seperti hub – hub kongsi satu segmen dengan semua port
501
Switch/Suis Dengan pensuisan, banyak stesen boleh hantar dengan serentak Menyediakan lebarjalur yang lebih tinggi Lebih mahal per port Secara ekonominya, ada yang sesuai guna hub, yang lain sesuai guna suis
502
Ringkasan Repeater bertindak sebagai amplifier dan hantar-semula isyarat analog Bridge terima kerangka keseluruhan kerangka dan hantar-semula Mengelakkan pertembungan pada segmen destinasi Tapis kerangka Pensuis membekalkan kelajuan LAN sepenuhnya kepada setiap port
503
Ringkasan NIC sambungkan komputer dengan rangkaian
terdapat banyak skima pendawaian fizikal untuk topologi rangkaian logikal
504
Rangkaian Komputer Setempat Wayarles (WLAN)
Ethernet Wayarles Bluetooth
505
Pengenalan Permintaan utk meyambungkan peranti tanpa wayar semakin tinggi WLan lazim diguna dlm kampus, bgnan pejabat, bahkan di tempat awam seperti kafe, stesen minyak, dll. WLan juga boleh dipasang di rumah utk mengunjurkan sambungan Internet kpd peranti-peranti mudah alih yg lain
506
IEEE Piawaian mentakrifkan spesifikasi yg merangkumi lapisan fizikal dan pautan data bg WLAN Senibina Lapisan Fizikal Lapisan Kawalan Capaian Media (MAC) Mekanisma Pengalamatan
507
Senibina WLAN : Set Perkhidmatan Asas(BSS)
BSS ditakrifkan sebgi blok asas WLAN Terdiri drp set stesen mudah alih/tetap & satu stesen pangkalan (access point -AP) BSS tanpa AP tidak blh hantar data ke BSS lain (dikenali : senibina ad-hoc) Stesen2 bersetuju utk menjadi sebhgn drp BSS
508
Senibina WLAN : Set Perkhidmatan Lanjutan (ESS)
509
Senibina WLAN:Set Perkhidmatan Lanjutan (ESS)
ESS terdiri drp >= 2 BSS dgn AP Lazimnya BSS dihubungkan melalui suatu sistem teragih iaitu LAN (wired) Sistem teragih bertindak sebagai penghubung kpd AP utk setiap BSS IEEE tidak mengenakan kekangan terhdp jenis sistem teragih – blh terdiri drp sebrg LAN (cth: Ethernet) Stesen dlm ESS: mudah alih & tetap Mudah alih: stesen biasa dlm BSS Tetap: AP yg merupakan sebhgn drp LAN Apabila BSS2 bersambung, senibina ini dipanggil rangkaian infrastruktur, dan stesen dlm BSS tidak perlukan AP utk berkomunikasi antara 1 sama lain Namun komunikasi antara 2 stesen dr 2 BSS berbeza lazimnya berlaku menerusi 2 AP
510
Jenis-jenis Stesen IEEE mentakrifkan 3 jenis stesen berasaskan pergerakannya: Pergerakan Tanpa-Peralihan Stesen tetap atau bergerak di dlm suatu BSS Pergerakan Peralihan-BSS Stesen blh bergerak dr 1 BSS ke BSS lain, teapi terhad dlm 1 ESS shj Pergerakan Peralihan-ESS Stesen blh bergerak dr 1 ESS ke ESS lain, tetapi IEEE tidak menjamin komunikasi akan kekal sepanjang pergerakan
511
Spesifikasi Lapisan Fizikal
IEEE mentakrifkan spesifikasi utk menukar bit ke isyarat (lapisan fizikal) Terdpt 5 spesifikasi dlm julat frekuensi radio
512
Frequency Hopping Spread Spectrum
Penjanaan isyarat dlm jalur 2.4 GHz ISM Penghantaran data guna 1 frekuensi pembawa utk jangkamasa tertentu dan meloncat ke frekuensi yg lain pula, dan seterusnya … Selepas N loncatan, kitaran berulang. Jika lebarjalur isyarat asal adalah B, lebarjalur sebaran spektrumnya : N x B Menyukarkan intipan, kadar data: 2 Mbps, guna modulasi FSK pd 1M baud/s
513
Direct Sequence Spread Spectrum
Juga dlm jalur 2.4-GHz ISM (industrial, scientific, medical) Setiap bit yg dihantar diganti dgn jujukan bit (kod cip) Utk elak penggunaan penimbal, masa utk hantar 1 kod cip perlu = masa utk hantar bit asal Jika bil. Bit dlm setiap kod cip = N, kadar data utk hantar cip kod = N x kadar data strim bit asal Tidak serupa spt CDMA krn ini implementasian pd lapisan fizikal Jujukan bit menggunakan keseluruhan jalur Kadar data 2 Mbps, guna modulasi PSK pd 1Mbaud/s
514
Lapisan MAC dlm piawaian IEEE 802.11
2 sub-lapisan MAC Fungsi Koordinasi Teragih (DCF) Fungsi Koordinasi Titik (PCF) – lebih kompleks hanya utk rangkaian infrastruktur
515
Kaedah Capaian : CSMA/CA
516
CSMA/CA dan Network Allocation Vector
NAV ialah cara CA diimplementasikan Bila RTS dihantar oleh 1 stesen (termasuk jangkamasa yg diperlukan utk guna saluran) Stesen lain akan mulakan NAV masing2 – masa harus tunggu sebelum boleh semak status talian Distributed IFS dan Short IFS adalah masa menunggu antara kerangka
517
Format Kerangka lapisan MAC
Persekitaran wayarles memp. tahap hingar tinggi, byk kerangka perlu hantaran semula Pecahkan kerangka supaya hanya perlu ganti kerangka bersaiz kecil (fragmentation)
518
Submedan dlm medan FC Field Explanation Version
The current version is 0. Type Type of information: management (00), control (01), or data (10). Subtype Defines the subtype of each type (see ). To DS Defined later. From DS More flag When set to 1, means more fragments. Retry When set to 1, means retransmitted frame. Pwr mgt When set to 1, means station is in power management mode. More data When set to 1, means station has more data to send. WEP Wired equivalent privacy. When set to 1, means encryption implemented. Rsvd Reserved.
519
Kerangka Kawalan
520
Nilai Submedan dlm Kerangka Kawalan
Subtype Meaning 1011 Request to send (RTS) 1100 Clear to send (CTS) 1101 Acknowledgment (ACK)
521
Submedan dlm medan FC To DS From DS Address 1 Address 2 Address 3
Destination station Source station BSS ID N/A 1 Sending AP Receiving AP
522
Mekanisma Pengalamatan : kes 1
Pengalamatan dlm sgt kompleks krn melibatkan byk AP Addr 1 : peranti berikutnya Addr 2 : peranti sebelumnya Addr 3 : peranti destinasi jika tak dinyatakan oleh Addr 1 Addr 4 : peranti asal jika != dgn Addr 2
523
Figure 15.12 Addressing mechanism: case 2
524
Figure 15.13 Addressing mechanism: case 3
525
Figure 15.14 Addressing mechanism: case 4
526
Bluetooth Teknologi WLAN direkabtk utk menyambungkan peranti pelbagai fungsi: telefon, PDA, kamera, pencetak, tetikus, earpiece, dll Ia merupakan suatu rangkaian ad hoc – blh dibtk secara spontan Peranti2 bluetooth saling mengesan utk membtk suatu rangkaian dipanggil piconet Bluetooth LAN juga blh dihubungkan ke Internet jika salah satu perantinya memp. keupayaan tersebut Piawaian : IEEE yg mentakrifkan rangkaian kawasan personal (PAN) wayarles yg merangkumi suatu bilik atau dewan
527
Senibina Rangkaian: Piconet
Piconet blh terdiri drp 8 stesen dgn salah satunya berfungsi sbgi master Peranti slave sinkronikan jam dan jujukan loncatan frekuensinya (hop) supaya sama dgn master Komunikasi antara master-slave blh jadi 1-1 atau 1-byk Slave blh bertukar keadaan dr aktif ke parkir dan sebaliknya
528
Senibina Rangkai : Scatternet
Piconet 1 Piconet 2
529
Scatternet Piconet boleh digabungkan membtk Scatternet
Stesen slave dlm 1 piconet akan menjadi master bagi piconet yg lain Stesen ini blh menerima mesej drp master (piconet 1) dan bertindak sbgi master (piconet 2) utk sampaikan kpd slave dlm piconet 2
530
Peranti Bluetooth Peranti bluetooth memp. transmitter radio jarak dekat Kadar data: 1Mbps dgn lebarjalur 2.4-GHz, oleh itu mungkin berlaku gangguan di antara WLAN IEEE b dan LAN Bluetooth
531
Lapisan Bluetooth Lapisan bluetooth tidak sepadan dgn model TCP/IP
Lapisan radio ~ lapisan fizikal Perantinya berkuasa rendah meliputi kwsan seluas 10 m Band: guna jalur 2.4-GHz ISM dibhgi kpd 79 saluran (1 MHz setiap satu)
532
Lapisan Bluetooth Bluetooth guna kaedah FHSS pd lapisan fizikal utk elakkan gangguan drp peranti atau rangkaian lain Bluetooth melakukan loncatan 1600 kali/s, bermakna ia menukar modulasi frekuensinya 1600 kali/s – beroperasi selama 625 μs utk setiap frekuensi Utk tukar bit ke isyarat, modulasi GFSK (Gaussian) Lapisan Baseband: hampir sama lapisan MAC dlm LAN dgn kaedah capaian Time Divison Duplexing-TDMA (sejenis komunikasi dupleks separa) Komunikasi hanya antara master-slave Tiada komunikasi langsung antara slave-slave
533
Komunikasi Single-slave
534
Komunikasi Multiple-slave
535
Format Kerangka
536
Format Paket Data L2CAP
537
Kaedah Capaian Dalam Rangkaian
Talian Khas (Capaian Titik-ke-titik) Perkongsian Talian (Capaian berbilang) Protokol Capaian
538
Dedicated Link or Shared Link
2 peranti di dlm satu rangkaian boleh dihubungkan oleh: Talian yg dikhaskan (dedicated) Talian yg dikongsi (shared)
539
Talian Khas (Titik-ke-titik)
Kaedah capaian untuk sambungan menggunakan dedicated link dikenali sbgi Capaian Titik-ke-titik Protokol yg lazim diguna utk capaian ini pula : Point-to-Point Protocol (PPP) Cth kegunaan: pengguna Internet membuat sambungan dr rumah ke ISP
540
Pengguna lazimnya menggunakan modem biasa (DSL atau kabel)
Talian telefon atau kabel TV menyediakan sambungan fizikal, tetapi utk mengawal dan mengurus pemindahan data protokol titik-ke-titik diperlukan
541
What PPP provides: Ia menakrifkan format kerangka yg diguna oleh kedua peranti dlm pertukaran Ia menakrifkan proses tawar-menawar di antara kedua peranti dlm mewujudkan sambungan dan melakukan pertukaran data Ia menakrifkan bgimana data lapisan rangkaian dikapsulkan di dlm kerangka pautan data Ia menakrifkan bgimana dua peranti boleh mengesahkan identiti masing2
542
Timbunan PPP (PPP Stack)
Wlupun PPP merupakan protokol lapisan pautan data, namun ia menggunakan beberapa protokol lain: Link Control Protocol Utk membuat, menyenggara, mengkonfigurasi dan menamatkan talian Authentication Protocol Utk mengesahkan identiti pengguna (cth: dail up session) PAP (password) dan CHAP (challenge handshake) Network Control Protocol Utk mengkapsulkan data (network layer protocol -> PPP frame)
543
Kerangka PPP –versi HDLC
544
Keadaan Peralihan dlm PPP
545
Timbunan Protokol
546
Pengkapsulan paket LCP dlm suatu kerangka
547
Password Authentication Protocol
548
Paket PAP
549
Challenge Handshake Authentication Protocol
550
Contoh CHAP
551
Kaedah Perkongsian Talian
Apabila berbilang stesen disambung menggunakan satu talian, protokol capaian berbilang diperlukan utk mengkoordinasikan capaian kpd talian
552
Terdpt beberapa prosedur utk memastikan :
Perkongsian Talian Terdpt beberapa prosedur utk memastikan : Setiap stesen boleh mencapai media (talian) Tiada 2 stesen yg mencapai media pd masa yg sama Tiada stesen yg menyampuk stesen lain Tiada stesen yg memonopoli capaian
553
Protokol Capaian Berbilang
Protokol Capaian Rawak Protokol Capaian Terkawal Protokol Saluran
554
Protokol Capaian Rawak
Setiap stesen berhak mencapai talian tanpa dikawal oleh stesen lain Jika > 1 stesen cuba mencapai talian, akan berlaku konflik dlm capaian (perlanggaran) dan kerangka akan dimusnahkan atau diubahsuai
555
Protokol Capaian Rawak
Utk mengelakkan atau menangani konflik ini, kita perlukan suatu protokol yang berupaya utk menjawab soalan: Bila suatu stesen blh mencapai talian? Apa tindakan stesen jika talian sedang sibuk? Bgimana stesen menentukan sama ada transmisinya berjaya atau gagal? Apa tindakan stesen jika berlaku konflik capaian?
556
Evolusi Kaedah Capaian Rawak
557
Multiple Access: ALOHA – Protokol Capaian Berbilang Pertama
Univ. of Hawaii (1970-an) utk rangkaian LAN radio(wayarles) dgn kadar data 9600bps Stesen pangkalan – pengawal terpusat Utk hantar data perlu melalui stesen pangkalan
558
Multiple Access : ALOHA
Protokol ALOHA mengikut peraturan: Capaian Berbilang : Mana2 stesen menghantar kerangka bila ia ada data utk dihantar Perakuan : Slps menghantar kerangka, stesen menunggu perakuan. Jika tiada yg diterima dlm jangkamasa tertentu, stesen menunggu (guna strategi backoff ) dan hantar semula Stesen berhenti jika telah mencuba beberapa kali
559
Prosedur Protokol ALOHA
560
Carrier Sense Multiple Access (CSMA)
Dibina utk meminimakan kebrgkalian berlakunya perlanggaran dgn mengesan media/talian sblm menggunakannya Setiap stesen perlu mendengar sebelum menghantar data Bgimanapun perlanggaran masih boleh berlaku krn propagation delay – masa yg diambil oleh bit pertama utk sampai ke destinasi
561
Perlanggaran dlm CSMA
562
Strategi Gigih Dgn strategi gigih-p, bergtg kpd kebrgkalian tersebut. Jika p=0.2, stesen mempunyai 20 kemungkinan (drp 100) utk menggunakan talian. Jika stesen mengesan talian sedang idle, ia akan janakan suatu no. rawak (1-100), jika no. tersebut < 20, stesen akan menghantar data
563
Carrier Sense Multiple Access/Carrier Detect (CSMA/CD)
CSMA tidak menakrifkan prosedur sekiranya berlaku perlanggaran Dlm CSMA/CD, mana2 stesen boleh menghantar data Stesen kemudian memantau talian utk mengetahui status penghantaran (berjaya/gagal) Jika berlaku perlanggaran, kerangka akan dihantar semula Bgimanapun utk elakkan perlanggaran drp berulang, ia menunggu (strategi backoff ) utk suatu jangkamasa Jangkamasa bertambah jika perlanggaran lebih kerap berlaku Diguna dlm rangkaian Ethernet tradisional
564
Prosedur CSMA/CD
565
Carrier Sense Multiple Access/ Collision Avoidance (CSMA/CA)
Kaedah ini berbeza kerana ia mengelak berlakunya perlanggaran Stesen menggunakan strategi gigih. Jika talian didapati dlm keadaan melahu (idle), stesen menunggu selama IFG (interframe gap) Stesen menunggu lagi utk suatu jangkamasa rawak Kemudian ia menghantar data dan menunggu perakuan utk suatu jangkamasa tertentu Jika tidak diterima, nilai backoff ditingkatkan dan talian didengar sebelum penghantaran semula Diguna dlm rangkaian WLAN
566
Prosedur CSMA/CA
567
Capaian Terkawal Stesen berunding dgn 1 sama lain utk menentukan stesen yg berhak menghantar data Stesen tidak boleh menghantar tanpa kebenaran stesen lain 3 kaedah yang popular: Berasaskan tempahan Berasaskan tinjauan Berasaskan token
568
Stesen perlu membuat tempahan sebelum menghantar data
Capaian Terkawal Berasaskan Tempahan Stesen perlu membuat tempahan sebelum menghantar data Masa dibahagikan kpd sela-sela Dlm setiap sela, kerangka tempahan akan mendahului kerangka data yg dihantar pd sela tersebut Dlm sistem yg terdiri dr n stesen, akan ada n slot mini yg mewakili setiap stesen Utk hantar data, setiap stesen perlu membuat tempahan dlm slot yg diperuntukkan utknya
569
Capaian Terkawal Berasaskan Tinjauan
Sesuai utk topologi dgn 1 stesen primer dan yg lainnya sekunder Pertukaran data mesti melalui stesen primer Stesen primer yg mengawal talian Jika primer bersedia menerima data, ia akan meninjau (tanya) stesen sekunder jika ada data utk dihantar : proses polling Jika ia ingin menghantar data, primer akan memberitahu sekunder sasaran supaya bersedia utk menerima data : proses selecting
570
Proses Memilih (Selecting)
571
Proses Meninjau (Polling)
572
Dlm kaedah ini stesen2 disusun dlm lingkaran seumpama cincin
Capaian Terkawal Berasaskan Token Stesen diberi kebenaran utk menghantar data bila ia menerima suatu kerangka khas yg dipanggil token Dlm kaedah ini stesen2 disusun dlm lingkaran seumpama cincin Setiap stesen ada predecessor dan successor Kerangka diterima dr predecessor dan dihantar kpd successor
573
Apabila data sedang dihantar, token akan mengelilingi lingkaran
Capaian Terkawal Berasaskan Token Apabila data sedang dihantar, token akan mengelilingi lingkaran Jika suatu stesen ingin menghantar data, ia perlu menunggu token, menyimpannya dan menghantar sebyk mana kerangka selagi masa utknya belum luput Token kemudian dilepaskan semula
574
Prosedur Penghantaran Token
575
Protokol Saluran Kaedah capaian berbilang yg mana lebarjalur talian dikongsi di antara stesen-stesen melalui pembahagian masa, frekuensi atau kod 3 protokol saluran yg popular: FDMA – lebarjalur dibhgi kpd jalur2 utk setiap stesen TDMA – seluruh lebarjalur merupakan 1 saluran, stesen diberi slot masa CDMA – berbeza dr FDMA krn hanya 1 saluran menggunakan seluruh lebarjalur, berbeza dr TDMA krn semua stesen boleh hantar data serentak – tiada perkongsian masa
576
CDMA Implementasiannya masih baru
Satu saluran membawa kesemua transmisi data secara serentak Berasaskan teori pengkodan yg mana setiap stesen diberi suatu kod – jujukan nombor dipanggil cip
577
Peraturan Pengenkodan
578
Pemultipleksan CDMA
579
Pendemultipleksan CDMA
580
Penjanaan Jujukan Cip Guna Jadual Walsh : W1 danW2N
581
Penjanaan Jujukan Cip
582
Example 1 Check to see if the second property about orthogonal codes holds for our CDMA example. Solution The inner product of each code by itself is N. This is shown for code C; you can prove for yourself that it holds true for the other codes. C . C = [+1, +1, -1, -1] . [+1, +1, -1, -1] = = 4 If two sequences are different, the inner product is 0. B . C = [+1, -1, +1, -1] . [+1, +1, -1, -1] = = 0
583
Example 2 Check to see if the third property about orthogonal codes holds for our CDMA example. Solution The inner product of each code by its complement is -N. This is shown for code C; you can prove for yourself that it holds true for the other codes. C . (-C ) = [+1, +1, -1, -1] . [-1, -1, +1, +1] = = -4 The inner product of a code with the complement of another code is 0. B . (-C ) = [+1, -1, +1, -1] . [-1, -1, +1, +1] = = 0
584
DETAILS OF PROTOCOLS The Zoo Protocol TCP IP
585
A programmer can create Internet application software without understanding the underlying network technology or communication protocols - we will take a different approach Understanding the Zoo Protocol
586
Transmission Control Protocol (TCP)
587
Protokol pada paras pengangkutan
Menghantar mesej dari proses klien kepada proses pelayan Bagaimana proses klien dapat mencapai perkidmatan daripada proses pelayan? Komunikasi antara-proses (interprocess) ini dilakukan melalui port protokol
588
Port Protokol Nombor port diumpukkan kepada proses oleh sistem pengoperasian Terdapat 216 port (0 hingga 65535) Terdapat 2 set port untuk protokol UDP untuk protokol TCP
589
Hos sun1.ftsm.ukm.my /etc/services
590
Untuk perkhidmatan piawai
Port well-known (1 – 1023) Untuk perkhidmatan piawai HTTP [80], SMTP[25], FTP[21, 22], POP3[110], Telnet [23] Ephemeral port (1024 – 65535) Diumpukkan secara dinamik Diumpukkan kepada proses klien Apabila proses klien tamat, port akan dibebaskan Senarai lengkap umpukkan port dapat dilihat dengan arahan /etc/services (pada *nix)
591
Transmission Control Protocol (TCP)
Menyediakan perkhidmatan penghantaran yang dipercayai Menggunakan port protokol untuk proses pengalamatan Untuk aplikasi yang memerlukan kebolehpercayaan spt: telnet, http, ftp dll
592
Format Pengepala TCP
593
Sambungan TCP Sambungan TCP dikenalpasti dengan titik hujung (nombor port) sambungan tersebut Untuk membuka sambungan TCP memerlukan kerjasama dua hala Klien akan membuat permintaan kepada satu port pada pelayan Pelayan akan membuka port dan memulakan sambungan
594
Jabat-tangan tiga arah
TCP menggunakan ‘jabat-tangan tiga arah’ ketika memulakan dan menamatkan hubungan untuk menyediakan kebolehpercayaan Tentukan kedua-dua nod bersedia dan selaraskan nombor jujukan rawak untuk sinkronikan hubungan
595
Memulakan Sambungan TCP
Guna segmen SYN untuk cipta satu sambungan Hos 1 hantar segmen SYN dan nombor jujukan rawak Hos 2 membalas segmen SYN, dengan menghantar ACK kepada Hos 1 dan nombor jujukan rawak Host 1 balas dengan ACK
597
Menamatkan Sambungan TCP
TCP guna segmen FIN untuk menamatkan sambungan Jabat tangan empat arah
598
User Datagram Protocol (UDP)
Merupakan protokol pengangkutan Menyediakan komunikasi tanpa hubungan yang tidak dapat diharap (unreliable) Paket mungkin hilang atau tidak mengikut urutan Tiada berpenimbal – menerima data dari aplikasi dan terus menghantarnya Digunakan apabila tiada kawalan ralat diperlukan Untuk proses seperti DNS [53], echo [7], tftp [69], SNMP[161]
599
Format UDP Datagram Pengepala Data Port sumber UDP Port destinasi UDP
Port sumber UDP (16 bit) Port destinasi UDP (16 bit) Panjang mesej UDP (16 bit) Checksum UDP (16 bit) Data Port sumber UDP Port destinasi UDP Panjang mesej UDP Checksum UDP Data
600
Internet Protocol (IP)
601
IP Protokol pada paras rangkaian
Menyediakan penghantaran paket secara komunikasi tanpa sambungan Menggunakan alamat IP untuk pengalamatan Menentukan laluan paket melalui satu atau lebih lompatan (hop) sepanjang laluan Menyediakan mekanisma yang terdiri dari Unit data yang dinamakan IP datagram Perisian untuk menghantar datagram Petua bagaimana komputer hos memproses datagram
602
Figure 19.2 Links in an internetwork
603
Bagaimana komunikasi dalam Internet ?
IP bertanggungjawab menyediakan penghantaran cara terbaik (best-effort) untuk paket/datagram Bagaimana komunikasi dalam Internet ? Lapisan pengangkutan ambil aliran data dan pecahkan kepada datagram Lapisan rangkaian hantar setiap datagram melalui Internet. Pemecahan kepada unit yang lebih kecil boleh berlaku sewaktu proses ini Pada destinasi, datagram akan dikumpulkan kembali oleh lapisan rangkaian kepada datagram asal dan dihantar kepada lapisan pengangkutan
604
Figure 19.4 Network layer at the source
605
Figure 19.5 Network layer at a router
606
Figure 19.6 Network layer at the destination
607
Pengalamatan Perlu satu format alamat yang seragam
Format alamat mestilah tidak bersandaran dengan format alamat perkakasan Alamat mestilah unik pada keseluruhan rangkaian (Internet) Badan yang mengawal pendaftaran alamat – Internet Information Center (InterNIC)
608
Alamat IP (IPv4) Diwakilkan oleh integer 32-bit
Menggunakan notasi dotted decimal quad Terdiri daripada 4 bahagian 8 bit Dipisahkan dengan noktah
609
Kelas Rangkaian Alamat IP diorganisasi mengikut kelas rangkaian
Kelas A: 0nnnnnnn.iiiiiiii.iiiiiiii.iiiiiiii Kelas B: 10nnnnnn.nnnnnnnn.iiiiiiii.iiiiiiii Kelas C: 110nnnnn.nnnnnnnn.nnnnnnnn.iiiiiiii Kelas D: 1110bbbb.bbbbbbbb.bbbbbbbb.bbbbbbbb Kelas E: untuk kegunaan masa depan Perwakilan: n – nombor rangkaian i – nombor hos b – id kumpulan
610
Julat Alamat untuk kenalpasti Kelas Alamat
611
Setiap alamat IP dibahagikan kepada dua bahagian
No. rangkaian (prefix) - menunjukkan rangkaian fizikal di mana komputer dihubungkan No. hos (suffix) - menunjukkan nombor unik komputer pada rangkaian Internet Corporation for Assigned Names and Numbers (ICANN) bertanggungjawab mengumpukkan kelas A, B dan C kepada organisasi
612
Kelas A, B dan C adalah kelas primari Kelas D untuk tujuan multicast,
Digunakan untuk pengalamatan hos yang biasa Kelas D untuk tujuan multicast, Untuk broadcast mesej Kelas E dikhaskan untuk tujuan masa depan Setiap hos mempunyai antaramuka alamat maya yang dikenali sebagai loopback interface iaitu juga dikenali sebagai localhost
613
Figure 19.19 A network with two levels of hierarchy
614
Kelemahan Sistem Alamat IP
Sebahagian hos mempunyai lebih dari satu alamat Kelas rangkaian adalah terlalu rigid Tidak cukup alamat IP untuk kembangan masa hadapan
615
Subnet (subrangkaian)
Alamat IP diorganisasi sebagai subnet bagi memudahkan pengurusan rangkaian Setiap subnet adalah set alamat yang ditentukan oleh Alamat subnet (cth: ) Subnet mask (cth: )
616
Satu rangkaian kampus mengandungi LAN untuk pelbagai jabatan
Subnet Satu rangkaian kampus mengandungi LAN untuk pelbagai jabatan
617
Figure 19.20 A network with three levels of hierarchy (subnetted)
618
Figure 19.21 Addresses in a network with and without subnetting
619
Contoh Subnet Bagi rangkaian Kelas B:
3 bit digunakan sebagai subnet menjadikan 15 subnet subnet mask: 13 bit lagi mewakili hos
620
Routing Jika hos destinasi tidak berada pada rangkaian yang sama, datagram akan dihantar ke gateway Bagaimana IP memilih laluan untuk menghantar datagram ke rangkaian jauh? Menggunakan jadual routing yang mempunyai maklumat next hop – iaitu nod lain dihubung secara terus kepada gateway
621
Contoh routing table netstat -nr
Routing Table: IPv4 Destination Gateway Flags Ref Use Interface U hme0 U hme0 default UG UH lo0
622
Figure 19.31 Default routing
623
Protokol Internet Version 6 (IPv6)
AKA Protokol Internet generasi akan datang (IPng) Panjang alamat ditambah kepada128 bit Membenarkan tambahan hos Web pada Internet Membenarkan perkembangan Internet
624
Diagnostic tools ping traceroute (pada microsoft: tracert) netstat -nr
Untuk menguji hubungan dengan hos Mengukur round trip time traceroute (pada microsoft: tracert) Menunjukkan laluan data dari hos ke destinasi netstat -nr Menunjukkan jadual routing
625
ipconfig (pada microsoft) ifconfig -a (pd *nix)
Menunjukkan no IP, subnet dan gateway komputer
626
Tools hostname domainname nslookup Nama komputer Nama domain
Network and Server Information Tools from Myloca (Telekom Malaysia)
627
Latihan Dapatkan satu komputer yang dihubungkan pada LAN di UKM. Tentukan alamat IP kelas rangkaian subnet mask pelayan DNS Tukarkan alamat IP di bawah kepada notasi dotted-decimal Tentukan kelas rangkaian bagi alamat berikut:
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.