Client/server. The (simple) Client/Server Connection using Stream Sockets: The Server 5 steps to building the server 1.Create a ServerSocket object registers.

Slides:



Advertisements
Similar presentations
Multiplexing/Demux. CPSC Transport Layer 3-2 Multiplexing/demultiplexing application transport network link physical P1 application transport network.
Advertisements

Using TCP sockets in Java Created by M Bateman, A Ruddle & C Allison As part of the TCP View project.
Jan Java Networking UDP Yangjun Chen Dept. Business Computing University of Winnipeg.
Network Programming Chapter 11 Lecture 6. Networks.
1 L54 Networking (3). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
Advanced Java Class Network Programming. Network Protocols Overview Levels of Abstraction –HTTP protocol: spoken by Web Servers and Web Clients –TCP/IP:
A CHAT CLIENT-SERVER MODULE IN JAVA BY MAHTAB M HUSSAIN MAYANK MOHAN ISE 582 FALL 2003 PROJECT.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
1 Java Networking – Part I CS , Spring 2008/9.
CS 491, 591 Networking in Java Summer Establishing a Simple Server (Using Stream Sockets) Creating a Java server –Create ServerSocket object ServerSocket.
1 L52 Networking (1). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
Client-Server Network Programming Session 2: Programming with Java and project A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science State.
 Pearson Education, Inc. All rights reserved. 1 CH24 Networking : OBJECTIVES In this chapter you will learn:  To understand Java networking.
1 L53 Networking (2). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
1 Multithreading. 2 Threads Program units that execute independently; multiple threads run “simultaneously” Virtual machine executes each thread for short.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L24 (Chapter 25) Networking.
Client/server. About this show This ppt has two parts. The first part provides a brief introduction to client/server programming in java using streams.
 Pearson Education, Inc. All rights reserved Networking.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
TCP/IP protocols Communication over Internet is mostly TCP/IP (Transmission Control Protocol over Internet Protocol) TCP/IP "stack" is software which allows.
NET0183 Networks and Communications Lecture 31 The Socket API 8/25/20091 NET0183 Networks and Communications by Dr Andy Brooks Lecture powerpoints from.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of socket.
 Socket  The combination of an IP address and a port number. (RFC 793 original TCP specification)  The name of the Berkeley-derived application programming.
VIII. UDP Datagrams and Sockets. The User Datagram Protocol (UDP) is an alternative protocol for sending data over IP that is very quick, but not reliable:
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
 TCP (Transport Control Protocol) is a connection-oriented protocol that provides a reliable flow of data between two computers.  TCP/IP Stack Application.
RGEC MEERUT(IWT CS703) 1 Java Networking RGEC Meerut.
Socket Programming in Java CS587x Lecture 4 Department of Computer Science Iowa State University.
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.
Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
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.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
1 Network Programming and Java Sockets. 2 Network Request Result a client, a server, and network Client Server Client machine Server machine Elements.
L 2 - 1 3( 1/ 20) : Java Network Programming. The Socket API The previous contents describe client-server interaction that application programs use when.
Dynamic Architectures (Component Reconfiguration) with Fractal.
1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 7 Application.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Java Server Programming Web Interface for Java Programs.
1 CSCD 330 Network Programming Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 9 Client-Server Programming.
Part 4: Network Applications Client-server interaction, example applications.
Project Scenario for OpX. High-level Overview In the Test GUI Controller, opXController, for the opX command there is conceptually a call to an appropriate.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
1 CSCD 330 Network Programming Fall 2013 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 8a Application.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.
Netprog: Client/Server Issues1 Issues in Client/Server Programming Refs: Chapter 27.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Simon Roberts, IBM Corp Advanced Java Programming CSE 7345/5345/ NTU 531 Multithreaded/Sockets/Server Welcome.
1 K. Salah Application Layer Module K. Salah Network layer duties.
Network Programming. These days almost all devices.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 33 Networking.
Socket Programming original by Joonbok Lee KAIST heavily adapted by /Jens.
Object-Orientated Analysis, Design and Programming
Echo Networking COMP
Threads in Java Two ways to start a thread
Thread Pools (Worker Queues) cs
Lecture 21 Sockets 1 (Not in D&D) Date.
Client-server Programming
Issues in Client/Server Programming
Multiplexing/Demux.
Exceptions and networking
Presentation transcript:

Client/server

The (simple) Client/Server Connection using Stream Sockets: The Server 5 steps to building the server 1.Create a ServerSocket object registers an available TCP/IP port and a maximum queue length : ServerSocket server=new ServerSocket(port#,queuelen); This is called the handshake point. If the queue is full the connection is refused. The process is known as “binding a server to a port”. Only one application at a time can be bound to a particular port.

Simple Server continued: Step 2 2. The server listens, or “blocks” for a client connection: Socket connection =server.accept(); The socket connection makes possible interaction with the client via I/O streams. The server interacts with a client at a different port than the handshake point, which makes possible multi-threaded servers (ie.,after connection is established, the server can spawn a thread to process this client and go on listening for another.

Simple Server continued: Step 3 3. The server gets I/O connections associated with the client socket. I/O across the connection is not really much different than other java i/o. ObjectInputStream input = new ObjectInputStream(connection.getInputStream()); ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream()); The server’s output stream is the client’s input stream, and visa versa.

Simple Server continued 4. Process the connection – this phase is application-specific and might involve a single message being sent, complicated objects being exchanged, a loop, whatever. 5. Close the connection by invoking close() method on the streams.

The (simple) Client/Server Connection using Stream Sockets: The Client 4 steps to building the client: 1. Establish a connection to the server: Socket connection =new Socket(serverIP,port#); A connection is returned if this step is successful, otherwise an IOException is thrown. Notice, the client needs to know where the server is (the server’s IP) while the server doesn’t know in advance the client’s address.

Simple Client continued: Step 2 3. The client gets I/O connections associated with the socket. ObjectInputStream input = new ObjectInputStream(connection.getInputStream()); ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream()); Other stream types can be used to wrap around these for manipulation different object types. Any serializable object can be passed via the IO connection.

Simple Client continued 3. Processing phase 4. Close the connection by invoking close() method on the streams. This is application specific- the client needs to know when the server is done so as to avoid an IOException (EOFException) trying to read past EOF mark.

server code (in slide notes) ernet programming/Server.htmlhttp://employees.oneonta.edu/higgindm/int ernet programming/Server.html

Client code ernet%20programming/Client.htmlhttp://employees.oneonta.edu/higgindm/int ernet%20programming/Client.html

ServerTest app: erverTest.htmlhttp://employees.oneonta.edu/higgindm/internet%20programming/S erverTest.html import javax.swing.JFrame; public class ServerTest { public static void main( String args[] ) { Server application = new Server(); // create server application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); application.runServer(); // run server application } // end main } // end class ServerTest

Clienttest.java app feeds a url: g/ClientTest.html g/ClientTest.html import javax.swing.JFrame; public class ClientTest { public static void main( String args[] ) { Client application; // declare client application // if no command line args if ( args.length == 0 ) application = new Client( " " ); // connect to localhost else application = new Client( args[ 0 ] ); // use args to connect application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); application.runClient(); // run client application } // end main }

Compile and run Compile 4 java files. Run ServerTest, then ClientTest Exercise: modify clienttest code so a url is entered on the command line. Run the client and server on different machines Hint: You can use c:\ipconfig \all to show a machine’s ip, if you can get to the command prompt Loop back URL is

Server window

Client window

Some communication

Client closes connection

Connectionless Client/server communication via datagrams While the connection-based client/server model is similar to the telephone, the datagram model is more like the post office. The message is posted in sequential numbered packets and re-assembled at the target location. Messages may arrive jumbled, or not at all. This example uses the UserDatagramProtocol (UDP) between client and server.

Server structure in datagram communication DatagramSocket socket;//use this datatype … try{ socket= new DatagramSocket(5000);// specify port# …}catch(SocketException se){…} Wait for packets: Byte data[]=new byte[100]; while(true){//forever loop try{ Datagram receivepacket=new DatagramPacket(data,data.length); socket.recieve(receivepacket); … }catch(IOException e){}

Datagram server continued //Send packet to client…also inside try catch for ioexception: Datagram sendpacket=new DatagramPacket(receivepacket.getData(),receivepacket.getLength(),receivepacket.getAddress(),receivepacket.getPort()); socket.send(sendpacket);

Datagram (packet) server The server uses two DatagramPackets – one to send and one to receive packets. This application uses java.net classes: java.net.DatagramPacket and java.net.DatagramSocket DatagramSocket is created in a try block where the server is bound to a port. Processing on the serverside involves an infinite loop waiting for packets. Clients must specify the server port when sending packets. Datagram method receive() blocks until a packet is received then stores the packet info in its Datagram argument. Methods are called to display sender’s IP, port, message length and the message itself.

Packets: 4 files %20programming/PacketServer.htmlhttp://employees.oneonta.edu/higgindm/internet %20programming/PacketServer.html %20programming/PacketClient.htmlhttp://employees.oneonta.edu/higgindm/internet %20programming/PacketClient.html %20programming/PacketServerTest.htmlhttp://employees.oneonta.edu/higgindm/internet %20programming/PacketServerTest.html %20programming/PacketClientTest.htmlhttp://employees.oneonta.edu/higgindm/internet %20programming/PacketClientTest.html

PacketClient frame

PacketServer frame

Threaded client/server Some background –LockSwingUtilities.invokeLater() –Scanner –Executor for threads –Synchronization using Locks

Scanner Scanner is “replacing” StringTokenizer. It is similar, versatile and easy to use. Deitel pg 59 has an example. import java.util.Scanner; … Scanner input=new Scanner(System.in); int x; x=input.nextInt();

SwingUtilities.invokeLater() Having multiple threads manipulate GUI content may not give expected results. Better to have the event-dispatching thread queue requests to display answers, change colors, and so on, and handle them in order. Here is a method to do it: SwingUtilities.invokeLater( new Runnable(){ public void run(){ …thread does stuff to GUI }});

Executor service for running threads Recommended thread construction in jdk1.5 is public class mythread extends Runnable{ public void run(){ //loop or whatever try{ Thread.sleep(sometime); …the rest of it }catch(InterruptedException e){…} } …}

Executor service for running threads Executor Service example Deitel’s text pg 1059 import java.util.concurrent.*; Thread a= new Thread(…);//not recommended //should be RunnableThingy a= new RunnableThingy(); Thread b= new Thread(…);//as above ExecutorService threadEx=Executors.newFixedThreadPool(2); //can run just two threads threadEx.execute(a); threadEx.execute(b); … theadEx.shutdown();

Executor service for running threads Runnables are managed and executed by a class that implements Executor interface. This has one method, (execute). An executor manages a thread pool. Executor assigns each runnable object to a thread in the pool. If there are none it may make a new thread (newCachedThreadPool) or queue the runnable for the next available thread as in the fixed thread pool.

Synchronization using Lock Example in Deitel text pg 1071 This is fairly similar to providing synchronized methods. import java.util.concurrent.locks.*

Synchronization using Lock import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.Condition; public class SynchronizedBuffer implements Buffer { // Lock to control synchronization with this buffer private Lock accessLock = new ReentrantLock(); // conditions to control reading and writing private Condition canWrite = accessLock.newCondition(); private Condition canRead = accessLock.newCondition(); private int buffer = -1; // shared by producer and consumer threads private boolean occupied = false;

Synchronization using Lock: set public void set( int value ) { accessLock.lock(); // lock this object try { while ( occupied ) { System.out.println( "Producer tries to write." ); displayState( "Buffer full. Producer waits." ); canWrite.await();// wait until buffer is empty } // end while buffer = value; // set new buffer value // producer cannot store new value until consumer retrieves current value occupied = true; displayState( "Producer writes " + buffer ); // signal thread waiting to read from buffer canRead.signal(); } // end try catch ( InterruptedException exception ) { exception.printStackTrace(); } // end catch finally { accessLock.unlock(); // unlock this object } // end finally } // end method set

Synchronization using Lock: get public int get() { int readValue = 0; // initialize value read from buffer accessLock.lock(); // lock this object // output thread information and buffer information, then wait try { // while no data to read, place thread in waiting state while ( !occupied ) { System.out.println( "Consumer tries to read." ); displayState( "Buffer empty. Consumer waits." ); canRead.await(); // wait until buffer is full } // end while // indicate that producer can store another value // because consumer just retrieved buffer value occupied = false; readValue = buffer; // retrieve value from buffer displayState( "Consumer reads " + readValue ); // signal thread waiting for buffer to be empty canWrite.signal(); } // end try // if waiting thread interrupted, print stack trace catch ( InterruptedException exception ) { exception.printStackTrace(); } // end catch finally { accessLock.unlock(); // unlock this object } // end finally return readValue; } // end method get // display current operation and buffer state } // end class SynchronizedBuffer

Threaded client/server code links below and in slide notes cTacToeServerTest.htmlhttp://employees.oneonta.edu/higgindm/internet%20programming/Ti cTacToeServerTest.html cTacToeServer.htmlhttp://employees.oneonta.edu/higgindm/internet%20programming/Ti cTacToeServer.html cTacToeClient.htmlhttp://employees.oneonta.edu/higgindm/internet%20programming/Ti cTacToeClient.html cTacToeClientTest.htmlhttp://employees.oneonta.edu/higgindm/internet%20programming/Ti cTacToeClientTest.html

TicTacToeServer In notes

TicTacToe client

Compile & run Compile the 4 files. Run TicTacToeServerTest first. You need to run 2 clients (players). A window opens for the server and a board appears for each client.

Client boards after play

Exercises Modify the client to connect to a server on another machine. “Fix” the server so it can tell when the game ends.

Socket project Modify the threaded client server to play your choice: Hexapawn on 4X4 or larger board Dominoes Othello A simple card game War, or maybe “21” First option may be easiest. Othello also isn’t too hard. Make sure the server recognizes whose move it is, allows only correct moves, and knows when the game is over (or when a client terminates).