Practical Session 11 Multi Client-Server Java NIO.

Slides:



Advertisements
Similar presentations
CS Network Programming CS 3331 Fall CS 3331 Outline Socket programming Remote method invocation (RMI)
Advertisements

Socket Programming ENTERPRISE JAVA. 2 Content  Sockets  Streams  Threads  Readings.
©2009 Operačné systémy Procesy. 3.2 ©2009 Operačné systémy Process in Memory.
Today’s topic Issues about sending structures with TCP. Server design alternatives: concurrent server and multiplexed server. I/O multiplexing.
Andrew Borg. The University of York. 1 Java NIO Andrew Borg.
A CHAT CLIENT-SERVER MODULE IN JAVA BY MAHTAB M HUSSAIN MAYANK MOHAN ISE 582 FALL 2003 PROJECT.
Java Threads A tool for concurrency. OS schedules processes Ready Running 200 Blocked A process loses the CPU and another.
System Programming Practical session 10 Java sockets.
System Programming Practical session 12 Reactor.
System Programming Practical session 11 Multiple clients server Non-Blocking I/O.
© Lethbridge/Laganière 2001 Chap. 3: Basing Development on Reusable Technology 1 Let’s get started. Let’s start by selecting an architecture from among.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
19-Aug-15 About the Chat program. 2 Constraints You can't have two programs (or two copies of the same program) listen to the same port on the same machine.
Practical Session 11 Multi Client-Server Java NIO.
Socket Programming -What is it ? -Why bother ?. Basic Interface for programming networks at transport level It is communication end point Used for inter.
CS 352-Socket Programming & Threads Dept. of Computer Science Rutgers University (Thanks,this slides taken from er06/
Socket Programming References: redKlyde ’ s tutorial set Winsock2 for games (gamedev.net)
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
Assignment 3 A Client/Server Application: Chatroom.
Cli/Serv.: Chat/121 Client/Server Distributed Systems v Objectives –discuss a client/server based chat system –mention two other ways of chatting.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
1 Web Based Programming Section 8 James King 12 August 2003.
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, VUW Networking COMP # 22.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Networking and Concurrency COMP.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Practical Session 12 Reactor Pattern. Disadvantages of Thread per Client It's wasteful – Creating a new Thread is relatively expensive. – Each thread.
Synchronization Methods in Message Passing Model.
Java Sockets Tutorial Rahul Malik Nov 12, 2005.
Socket Programming Lab 1 1CS Computer Networks.
Prepared by Dr. Jiying Zhao University of Ottawa Canada.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
Java Server Sockets ServerSocket : Object to listen for client connection requests Throws IOException accept() method to take the client connection. Returns.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Topics to be covered: Java Packages Thread Example Java Socket Programming.
I/O Multiplexing Chap 6. I/O Models  Blocking I/O Model  Nonblocking I/O Model  I/O Multiplexing Model  Signal Driven I/O Model  Asynchronous I/O.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Simon Roberts, IBM Corp Advanced Java Programming CSE 7345/5345/ NTU 531 Multithreaded/Sockets/Server Welcome.
SPL/2010 Reactor Design Pattern 1. SPL/2010 Overview ● blocking sockets - impact on server scalability. ● non-blocking IO in Java - java.niopackage ●
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
The Echo Server Problem. Contents  Basic Networking Concepts  The Echo Server Problem.
Threads in Java Two ways to start a thread
Thread Pools (Worker Queues) cs
Thread Pools (Worker Queues) cs
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Block 15 Developing the Calculator application
Java Byte IPC: Part 6-Summary
Implementation CAN Communication Engine
Reactor Design Pattern
Clients and Servers 19-Nov-18.
null, true, and false are also reserved.
Clients and Servers 1-Dec-18.
Application Protocols
.Net Sockets.
Application Protocols
Y. Richard Yang 10/9/2018 Network Applications: High-Performance Server Design (Async Select NonBlocking Servers)
IO Package in Java.
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Clients and Servers 19-Jul-19.
Clients and Servers 13-Sep-19.
The reactor design pattern
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Thread per client and Java NIO
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Presentation transcript:

Practical Session 11 Multi Client-Server Java NIO

Supporting Multiple Clients The basic flow of logic in such a server is this: while (true) { accept a connection; create a thread to deal with the client; } The thread reads from and writes to the client connection as necessary.

The Server Interface interface ServerProtocol: – String processMessage(String msg); – boolean isEnd(String msg); In order to organize the work of the Server, and to allow several protocols, we create an interface: – processMessage: a function that decides what to do with the content received. – isEnd: returns true if the message equals our ‘exit’ command.

ConnectionHandler In order to allow more than one client to connect to our server, we need to run each connection in its own thread. ConnectionHandler is a Runnable that handles one connection. Each client that wishes to connect to our server initiates the connection. The server accepts the connection from the client. The socket returned is sent to the ConnectionHandler object. ConnectionHandler is run as a Thread. Server goes back to blocking mode, waiting for a new connection.

MultiClient – Server Implementation ServerProtocol [Interface] – processMessage – isEnd EchoProtocol implements ServerProtocol – processMessage: message received is returned – isEnd: returns true if message is ‘bye’ ConnectionHandler [Runnable] – Receives messages from client [msg = in.readLine()] – Processes message [using process()] using EchoProtocol If message is ‘bye’, exits thread [protocol.isEnd(msg)] Else, message is sent back to client [out.println(response)] – Sends returned result from processing to client. MultipleClientProtocolServer [Runnable] – Our server – runs as a thread – Creates ServerSocket, listens to a port – Runs ConnectionHandler in a thread once accept() returns a socket.

Java Non-blocking IO In our examples, the server gets stuck on – msg = in.readLine() – clientSocket = serverSocket.accept() – out.println(msg) //writing faster than the other side can read You cannot do something else while these methods are blocking. (process client messages, handle other clients etc.).

Java Non-blocking IO Solution? java.nio. The package is an efficient InputOutput package, which supports Non-blocking IO. NIO Concepts: – Channels – Buffers – Selectors Tutorial:

Channels [our sockets] An Object you can read from and write to. Channels can be either blocking (by default) or non-blocking. SocketChannel: – – Same as regular Socket object. – Difference: read(), write() can be non-blocking. ServerSocketChannel: – tml – accept() returns SocketChannel – Same as regular ServerSocket object. – Difference: accept() can be non-blocking. Does not block until a client connects. Checks if a client is trying to connect, if so returns a new socket, otherwise returns null!

Setting up ServerSocketChannel and SocketChannel ServerSocketChannel : – int port = 9999; – ServerSocketChannel ssChannel = ServerSocketChannel.open(); – ssChannel.configureBlocking(false); – ssChannel.socket().bind(new InetSocketAddress(port)); SocketChannel: – SocketChannel sChannel=SocketChannel.open(); – sChannel.connect(new InetSocketAddress("host/ip", 9999)); – sChannel.configureBlocking(false);

Buffers [our containers] The objects which hold the data to be sent and data received. Channels know how to read and write into Buffers, and buffers can read and write into other buffers. Java NIO comes with the following Buffer types: – ByteBuffer – CharBuffer – DoubleBuffer – FloatBuffer – IntBuffer – LongBuffer – ShortBuffer

Creating Buffers We'll be using ByteBuffer. These are buffers that hold bytes. Creating a new ByteBuffer: [Method I] – final int NUM_OF_BYTES = 1024; – ByteBuffer buffer = ByteBuffer.allocate(NUM_OF_BYTES); Creating a new ByteBuffer: [Method II] – String message = “Sentence to write into buffer”; – ByteBuffer buffer = ByteBuffer.wrap(message.getBytes(),”UTF-8”);

Buffer Markers Each buffer has capacity, limit, and position markers. Capacity: – Being a memory block, a Buffer has a certain fixed size, also called its "capacity". – You can only write capacity bytes, longs, chars etc. into the Buffer. – Once the Buffer is full, you need to empty it (read the data, or clear it) before you can write more data into it. Position: – Writing data to buffer: Initially the position is 0. When a byte, long etc. has been written into the Buffer the position is advanced to point to the next cell in the buffer to insert data into. Position can maximally become capacity - 1. – Reading data from buffer: When you flip a Buffer from writing mode to reading mode, the position is reset to 0. As you read data from the Buffer you do so from position, and position is advanced to next position to read. Limit: – In write mode: The limit of a Buffer is the limit of how much data you can write into the buffer. The limit is equal to the capacity of the Buffer. – When flipping the Buffer into read mode: The limit means the limit of how much data you can read from the buffer. When flipping a Buffer into read mode, limit is set to write position of the write mode. In other words, you can read as many bytes as were written (limit is set to the number of bytes written, which is marked by position).

Illustration

Usage Example

read/write operations

Buffer Flipping The flip() method switches a Buffer from writing mode to reading mode. Calling flip() sets the position back to 0, and sets the limit to where position just was. The position marker now marks the reading position, and limit marks how many bytes were written into the buffer - the limit of how many bytes, chars etc. that can be read. Example: – You create a ByteBuffer. – Write data into the buffer. – Flip() – Send the buffer to the channel.

Buffer IO Operations Reading from a channel to a buffer: numBytesRead = socketChannel.read(buf); – Contents found in socketChannel are read from their internal container object to our buffer. Writing from a buffer to a channel: numBytesWritten = socketChannel.write(buf); – Contents from our buf object are written to the socketChannel’s internal container to be sent. If read or write returns -1, it means that the channel is closed. Read and write operations on Buffers update the position marker accordingly.

More ByteBuffer Methods clear(): – Makes a buffer ready for a new sequence of channel-read or relative put operations. – Sets the limit to the capacity. – Sets the position to zero. rewind(): – Makes a buffer ready for re-reading the data that it already contains. – Leaves the limit unchanged. – Sets the position to zero.

StringMessageTokenizer Interface void addBytes(ByteBuffer bytes); – Receives a Buffer of bytes containing data to be converted to chars. boolean hasMessage(); Is there a complete message ready? String nextMessage(); – Get the next complete message if it exists, advancing the tokenizer to the next message.

FixedSeparatorMessageTokenizer FixedSeparatorMessageTokenizer(String separator, Charset charset) – The constructor. – Between two messages in the buffer we have a separator. – Messages are encoded [chars to bytes] and decoded [bytes to chars] using the given charset [ASCII, UTF-8] public synchronized void addBytes(ByteBuffer bytes): – Array of bytes received is converted to string and concatenated to the ones before it. public synchronized boolean hasMessage(): – Checks if the buffer has a complete message, if so true, otherwise false. [done by checking if the separator exists in the string array] public synchronized String nextMessage() – Returns the next complete message in the buffer.

NIO Echo Client ient

C++ Echo Client Connect a socket to a host and port: boost::asio::ip::tcp::socket socket_; boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(host_), port_); boost::system::error_code error; socket_.connect(endpoint, error); Read from socket: boost::asio::buffer(startingPointPointer, SizeToReadInBytes, exception) //exception is optional //tmp holds the number of bytes read so far; bytes: an array of chars to read the received bytes from socket_.read_some(boost::asio::buffer(bytes+tmp, bytesToRead-tmp), error) Write to socket: socket_.write_some(boost::asio::buffer(bytes + tmp, bytesToWrite - tmp), error) Example: – 05_Boost_Echo_Client