Socket based client server application
Download
1 / 104

Socket-based Client-Server Application - PowerPoint PPT Presentation


  • 96 Views
  • Uploaded on
  • Presentation posted in: General

Socket-based Client-Server Application. Client-Server application architecture Choosing services – Connectionless atau Connection-oriented. Evolution of Application Architecture. 3-tier Client-server application architecture. Internet Protocol and Network Application.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Socket-based Client-Server Application ' - lee-humphrey


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Socket based client server application

Socket-based Client-Server Application

Client-Server application architecture

Choosing services – Connectionless atau Connection-oriented

norly@ftsm.ukm.my




Internet protocol and network application
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

norly@ftsm.ukm.my


Client server model
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

norly@ftsm.ukm.my


Features of a client
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

norly@ftsm.ukm.my


Features of a server
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

norly@ftsm.ukm.my


Transport protocol and client server
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

norly@ftsm.ukm.my



Several services on a server
Several Services on a Server

norly@ftsm.ukm.my


Identifying a service
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

norly@ftsm.ukm.my


Connection oriented and connectionless transport protocol
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

norly@ftsm.ukm.my


Socket based client server application
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.

norly@ftsm.ukm.my


Socket based client server application

  • 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.

norly@ftsm.ukm.my


Socket based client server application

norly@ftsm.ukm.my


Advantages of udp
Advantages of UDP Packets that are corrupt or only partially delivered are discarded.

  • 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.

norly@ftsm.ukm.my


Socket based client server application

norly@ftsm.ukm.my


Java support for udp
Java Support for UDP machine.

  • Two classes are provided:

    • DatagramPacket class (java.net)

    • DatagramSocket class (java.net)

norly@ftsm.ukm.my


Datagrampacket class
DatagramPacket machine. 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.

norly@ftsm.ukm.my


Socket based client server application

  • When a machine.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[])

norly@ftsm.ukm.my


Creating a datagrampacket
Creating a machine.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);

norly@ftsm.ukm.my


Socket based client server application

  • Constructor to use for sending a machine.DatagramPacket to a remote machine

    DatagramPacket(byte[] buffer, int length, InetAddress dest_addr, int dest_port)

  • Example:

    DatagramPacket packet;

    InetAddress addr;

    addr = InetAddress.getByName("192.168.0.1");

    packet = new DatagramPacket(new byte[128], 128,addr, 2000);

norly@ftsm.ukm.my


Datagrampacket methods
DatagramPacket machine. 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)

norly@ftsm.ukm.my


Datagramsocket class
DatagramSocket machine. 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.

norly@ftsm.ukm.my


Socket based client server application

  • Each machine.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.

norly@ftsm.ukm.my


Creating a datagramsocket
Creating a machine.DatagramSocket

  • Constructor to use for creating a client DatagramSocket:

    DatagramSocket() throws java.net.SocketException

  • Example:

    DatagramSocket socket;

    try {

    socket = new DatagramSocket();

    } catch (SocketException exception) {

    }

norly@ftsm.ukm.my


Socket based client server application

  • Constructor to use for creating a server machine.DatagramSocket:

    DatagramSocket(int port) throws java.net.SocketException

  • Example:

    DatagramSocket socket;

    try {

    socket = new DatagramSocket(2000);

    } catch (SocketException exception) {

    }

norly@ftsm.ukm.my


Datagramsocket methods
DatagramSocket machine. 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

norly@ftsm.ukm.my


Socket based client server application

  • int getSendBufferSize() throws java.net.SocketException machine.

  • 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

norly@ftsm.ukm.my


Listening for udp packets
Listening for UDP Packets machine.

  • 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.

norly@ftsm.ukm.my


Socket based client server application

Packet machine.

Reads packets

DatagramSocket

DatagramPacket

Translates packets

Into a DatagramPacket

UDP application

norly@ftsm.ukm.my


Socket based client server application

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();

norly@ftsm.ukm.my


Socket based client server application

ByteArrayInputStream packets.

  • Java I/O streams are usually used to access the contents of the byte array in a DatagramPacket. See example later.

DataInputStream

DatagramPacket

IP address (java.net.InetAddr)

Port address (int)

Packet data (byte[])

UDP

application

norly@ftsm.ukm.my


Sending udp packets
Sending UDP Packets 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.

norly@ftsm.ukm.my


Socket based client server application

DatagramSocket packets.

Binds to a

UDP port

UDP application

Send DatagramPacket

using DatagramSocket

Packet

Constructs

packet

DatagramPacket

norly@ftsm.ukm.my


Socket based client server application

DatagramPacket packet; packets.

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();

  • The following code illustrates the process for sending UDP packets.

norly@ftsm.ukm.my


User datagram protocol example
User Datagram Protocol Example packets.

  • Run receiving application

    java PacketReceiveDemo

  • Run sending application

    java PacketSendDemo

norly@ftsm.ukm.my






Socket based client server application

DatagramPacket packets.

PacketSendDemo

PrintStream

print(str)

ByteArrayOutputStream

toByteArray()

send(packet)

DatagramSocket

norly@ftsm.ukm.my


Socket based client server application

DatagramPacket packets.

DatagramSocket

receive(packet)

ByteArrayInputStream

getData()

read()

PacketReceiveDemo

norly@ftsm.ukm.my


Building a udp client server
Building a UDP Client/Server packets.

  • Run echo server

    java EchoServer

  • Run echo client

    java EchoClient

norly@ftsm.ukm.my


Algorithm for echo server
Algorithm for Echo Server packets.

  • Create socket

  • Create an empty packet

  • Repeat the following forever

    • Wait for a packet

    • Send the packet back to sender

norly@ftsm.ukm.my


Algorithm for echo client
Algorithm for Echo Client packets.

  • 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

norly@ftsm.ukm.my


Overcoming udp limitations
Overcoming UDP Limitations packets.

  • UDP limitations:

    • Lack of Guaranteed Delivery

    • Lack of Guaranteed Packet Sequencing

    • Lack of Flow Control

norly@ftsm.ukm.my


Lack of guaranteed delivery
Lack of Guaranteed Delivery packets.

  • 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).

norly@ftsm.ukm.my


Socket based client server application

  • If guaranteed delivery is required, packets.

    • avoid packet-based communication, and use a more suitable transport mechanism (e.g. TCP).

    • send acknowledgement to sender after receiving packets.

norly@ftsm.ukm.my


Lack of guaranteed packet sequencing
Lack of Guaranteed Packet Sequencing packets.

  • 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.

norly@ftsm.ukm.my


Lack of flow control
Lack of Flow Control packets.

  • 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.

norly@ftsm.ukm.my


Transmission control protocol

Transmission Control Protocol packets.

norly@ftsm.ukm.my


Overview
Overview packets.

  • 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.

norly@ftsm.ukm.my


Socket based client server application

Establish a virtual connection packets.

Transmit data back and forth

Terminate the connection

norly@ftsm.ukm.my


Socket based client server application

  • 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.

norly@ftsm.ukm.my


Socket based client server application

  • TCP sockets are different from UDP sockets: between machines.

    • 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.

norly@ftsm.ukm.my


Advantages of tcp over udp
Advantages of TCP over UDP between machines.

  • 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.

norly@ftsm.ukm.my


Socket based client server application

  • Reliability between machines.

    • 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.

norly@ftsm.ukm.my


Socket based client server application

  • Ease of Use between machines.

    • 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.

norly@ftsm.ukm.my


Communication using ports
Communication Using Ports between machines.

  • 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

norly@ftsm.ukm.my


Socket based client server application

norly@ftsm.ukm.my


Socket operations
Socket Operations number in the range 1 - 65535.

  • 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

norly@ftsm.ukm.my


Socket based client server application

norly@ftsm.ukm.my


Tcp and the client server paradigm
TCP and the Client/Server Paradigm that will bind to a specific port number. Normally used only in servers, this socket can perform the following operations:

  • 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.

norly@ftsm.ukm.my


Socket based client server application

  • 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.

norly@ftsm.ukm.my


Network clients
Network Clients connection is established. UDP applications may both initiate and receive requests on the same socket.

  • 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.

norly@ftsm.ukm.my


Socket based client server application

norly@ftsm.ukm.my


Network servers
Network Servers E.g. a web server uses port 80.

  • 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.

norly@ftsm.ukm.my


Socket based client server application

  • 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.

norly@ftsm.ukm.my


Tcp sockets and java
TCP Sockets and Java others can handle many connections concurrently, through the use of threads.

  • 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.

norly@ftsm.ukm.my


Socket class
Socket others can handle many connections concurrently, through the use of threads. Class

  • Socket objects represent client sockets, and is a communication channel between two TCP communications ports belonging to one or two machines.

norly@ftsm.ukm.my


Socket based client server application

  • There are several constructors for the others can handle many connections concurrently, through the use of threads.Socket class.

  • The easiest way to create a socket is shown below:

    Socket mySocket;

    try {

    mySocket = new Socket("www.aol.com", 80);

    } catch (Exception e) {

    }

norly@ftsm.ukm.my


Socket based client server application

  • Some of the other constructors: others can handle many connections concurrently, through the use of threads.

    • Socket(InetAddress addr, int port)

      • Throws java.io.IOException, java.lang.SecurityException

    • Socket(InetAddress rAddr, int rPort, InetAddress lAddr, int lPort)

      • Throws java.io.IOException, java.lang.SecurityException

    • Socket(String rHost, int rPort, InetAddress lAddr, int lPort)

      • Throws java.net.UnknownHostException, java.io.IOException, java.lang.SecurityException

norly@ftsm.ukm.my


Using a socket
Using a Socket others can handle many connections concurrently, through the use of threads.

  • Refer section 6.4.2 (pg 150) for a description of some of the methods of the Socket class.

norly@ftsm.ukm.my


Reading from and writing to tcp sockets
Reading from and Writing to TCP Sockets others can handle many connections concurrently, through the use of threads.

  • 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.

norly@ftsm.ukm.my


Socket based client server application

  • Socket socket; others can handle many connections concurrently, through the use of threads.

  • InputStreamReader isr;

  • BufferedReader br;

  • PrintStream ps;

  • try {

    • socket = new Socket("www.aol.com",80);

    • isr = new InputStreamReader(socket.getInputStream());

    • br = new BufferedReader(isr);

    • ps = new PrintStream(socket.getOutputStream());

  • } catch (Exception e) {

  • }

  • Example:

norly@ftsm.ukm.my


So timeout socket option
SO_TIMEOUT Socket Option others can handle many connections concurrently, through the use of threads.

  • 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.

norly@ftsm.ukm.my


Socket based client server application

  • Use the others can handle many connections concurrently, through the use of threads.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.

norly@ftsm.ukm.my


Creating a tcp server
Creating a TCP Server others can handle many connections concurrently, through the use of threads.

  • The given example is a TCP server which returns the current day and time to the client.

norly@ftsm.ukm.my


Socketserver class
SocketServer others can handle many connections concurrently, through the use of threads. 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.

norly@ftsm.ukm.my


Socket based client server application

norly@ftsm.ukm.my


Creating a serversocket
Creating a whereas server sockets are capable of fulfilling the requests of multiple clients.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.

norly@ftsm.ukm.my


Socket based client server application

  • There are several constructors for the whereas server sockets are capable of fulfilling the requests of multiple clients.ServerSocket class.

  • The easiest way to create a socket is shown below:

    ServerSocket mySocket;

    try {

    mySocket = new ServerSocket(80);

    } catch (Exception e) {

    }

norly@ftsm.ukm.my


Socket based client server application

  • Some of the other constructors: whereas server sockets are capable of fulfilling the requests of multiple clients.

    • 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)

      • Throws java.io.IOException, java.lang.SecurityException

      • Allocates sufficient space to the queue to support the specified number of client sockets.

norly@ftsm.ukm.my


Using a serversocket
Using a ServerSocket whereas server sockets are capable of fulfilling the requests of multiple clients.

  • Refer section 6.6.2 (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.

norly@ftsm.ukm.my


Accepting and processing requests from tcp clients
Accepting and Processing Requests from TCP Clients whereas server sockets are capable of fulfilling the requests of multiple 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.

norly@ftsm.ukm.my


Socket based client server application

ServerSocket server; whereas server sockets are capable of fulfilling the requests of multiple clients.

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()));

}

  • Example:

norly@ftsm.ukm.my


Tcp socket client server ali baba
TCP Socket Client-Server : whereas server sockets are capable of fulfilling the requests of multiple clients.ALI BABA…

norly@ftsm.ukm.my


Ali baba client server
ALI BABA Client-Server whereas server sockets are capable of fulfilling the requests of multiple clients.

norly@ftsm.ukm.my


Client application
Client Application whereas server sockets are capable of fulfilling the requests of multiple clients.

  • In this example, there are 2 java programs

  • The client program is implemented as a class NyietInSengClient

norly@ftsm.ukm.my


Socket based client server application

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();

}

}

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(newInputStreamReader(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.");

System.exit(1);

}

norly@ftsm.ukm.my


Server application
Server Application InputStreamReader(System.in));

  • 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

norly@ftsm.ukm.my


Socket based client server application

PrintWriter out = new PrintWriter( InputStreamReader(System.in));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);

out.println(outputLine);

if (outputLine.equals("tata titi tutu"))

break;

}

out.close();

in.close();

clientSocket.close();

serverSocket.close();

}

}

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;

try {

clientSocket = serverSocket.accept();

} catch (IOException e) {

System.err.println("Accept failed.");

System.exit(1);

}

norly@ftsm.ukm.my


Protocol class part of server app
Protocol class (part of server app) InputStreamReader(System.in));

  • 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.

norly@ftsm.ukm.my


Server app
Server App. InputStreamReader(System.in));

  • 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);

    }

norly@ftsm.ukm.my


Socket based client server application

Server App. InputStreamReader(System.in));

  • 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.

norly@ftsm.ukm.my


Socket based client server application

  • 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);

    }

norly@ftsm.ukm.my


Server app1
Server App. then a

  • 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.

norly@ftsm.ukm.my


Read write process
Read/Write Process then a

  • 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;

norly@ftsm.ukm.my


Server app2
Server App. then a

  • 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).

norly@ftsm.ukm.my


Server app3
Server App. then a

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).

norly@ftsm.ukm.my


Socket based client server application

  • 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.

norly@ftsm.ukm.my


Communication protocol of alibaba client server
Communication Protocol of AliBaba Client-Server a few comments.

  • Following is the implementation of the protocol:

norly@ftsm.ukm.my


Socket based client server application

if (state == WAITING) { a few comments.

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;

} else {

theOutput = "Sepatutnya awak cakap \"" +

clues[currentJoke] +

" mana?\"" +

"! Cuba lagi. NyietInSeng MatekAji Semar Ngiseng!";

state = SENTTOKTOK;

}

} else if (state == ANOTHER) {

if (theInput.equalsIgnoreCase("y")) {

theOutput = "NyietInSeng MatekAji Semar Ngiseng!";

if (currentJoke == (NUMJOKES - 1))

currentJoke = 0;

else

currentJoke++;

state = SENTTOKTOK;

} else {

theOutput = "tata titi tutu";

state = WAITING;

}

}

return theOutput;

}

}

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;

norly@ftsm.ukm.my


ad
  • Login