CSE 219 Computer Science III Network Programming (Application Layer) Reference:

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.
Multiplexing/Demux. CPSC Transport Layer 3-2 Multiplexing/demultiplexing application transport network link physical P1 application transport network.
Socket Programming By Ratnakar Kamath. What Is a Socket? Server has a socket bound to a specific port number. Client makes a connection request. Server.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
Basic Socket Programming with Java. What is a socket?  Generally refers to a stream connecting processes running in different address spaces (across.
Socket Programming.
1 Java Networking – Part I CS , Spring 2008/9.
WECPP1 Java networking Jim Briggs based on notes by Amanda Peart based on Bell & Parr's bonus chapter
1 Networking with Java 2: The Server Side. 2 Some Terms Mentioned Last Week TCP -Relatively slow but enables reliable byte-stream transmission UDP -Fast.
1 Programming Section 9 James King 12 August 2003.
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
Client/Server In Java An Introduction to TCP/IP and Sockets.
© 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.
Networking Support In Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
Socket Programming -What is it ? -Why bother ?. Basic Interface for programming networks at transport level It is communication end point Used for inter.
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
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.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Silberschatz, Galvin and Gagne  2002 Modified for CSCI 399, Royden, Operating System Concepts Operating Systems Lecture 12 Communicating over.
DBI Representation and Management of Data on the Internet.
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
RGEC MEERUT(IWT CS703) 1 Java Networking RGEC Meerut.
LAB 1CSIS04021 Briefing on Assignment One & RMI Programming February 13, 2007.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
1 Streams Files are a computer’s long term memory Need ability for programs to –get information from files –copy information from program variables to.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
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.
Web Design & Development 1 Lec - 21 Umair Javed. Web Design & Development 2 Socket Programming.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, VUW Networking COMP # 22.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
1 cs205: engineering software university of virginia fall 2006 Network Programming* * Just enough to make you dangerous Bill Cheswick’s map of the Internet.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
Li Tak Sing COMPS311F. RMI callbacks In previous example, only the client can initiate a communication with the server. The server can only response to.
Field Trip #25 Creating a Client/Server By Keith Lynn.
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.
By Vivek Dimri. Basic Concepts on Networking IP Address – Protocol – Ports – The Client/Server Paradigm – Sockets The Java Networking Package – The InetAddress.
CSI 3125, Preliminaries, page 1 Networking. CSI 3125, Preliminaries, page 2 Networking A network represents interconnection of computers that is capable.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
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.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
CSE 501N Fall ‘09 22: Introduction to Networking November Nick Leidenfrost.
Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Li Tak Sing COMPS311F. Case study: a multithreaded chat server The source contains 3 files: ChatServer //the chat server ChatThread //the thread on the.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
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.
Echo Networking COMP
Lecture 21 Sockets 1 (Not in D&D) Date.
MCA – 405 Elective –I (A) Java Programming & Technology
Networking with Java 2.
An Introduction to TCP/IP and Sockets
PRESENTED To: Sir Abid………. PRESENTED BY: Insharah khan………. SUBJECT:
Clients and Servers 19-Nov-18.
Clients and Servers 1-Dec-18.
CS18000: Problem Solving and Object-Oriented Programming
Presentation transcript:

CSE 219 Computer Science III Network Programming (Application Layer) Reference:

What’s a server? A program running on a machine connected to the Internet that can serve information to other machines –identified by an IP address (ex: ) like a phone number for computers on the Net anyone know the local IP address? – –host names (ex: sparky.ic.sunysb.edu) are translated into IP addresses by Domain Name Servers (DNS) anyone know the local host name? –"localhost" –to convert back and forth, see:

What’s a client? A machine connected to the Internet that requests information from servers –download server files (like Web pages) –run server applications Commonly used client applications: –browser –SSH –And many more

We’re talking 2 applications To employ a client/server architecture, you need at least two applications –this means at least two main methods the client program the server program presume they would be running different machines

How does a server work? Servers have numbered doors (ports) –servers have ports –ports can be opened or closed A server program listens for client requests at specific open ports –called binding to a port (or ports) –different server programs listen at different ports A requesting client program must specify the correct port number –browsers use port 80 –SSH uses port 22 java.net.ServerSocket : Java class for a basic server –accept() – method to start listening when called, the server sits and waits (perhaps forever) for a client to make a request returns a Socket object

Binding to a port Has the effect of registering the server with the system to receive all data destined for that port ServerSocket server = new ServerSocket(8000); … Socket connection = server.accept();

Types of ports Well-known ports (0 – 1023) –Assigned by the IANA –On most systems can only be used by root processes or programs executed by privileged users HTTP on port 80 SSH on port 22 FTP on port 21 Full list: Registered ports (1024 – 49151) –can be used by any programs if the firewall permits it –we’ll use these for our project Dynamic and/or Private ports (49152 – 65535) –not commonly used, are common range used by trojan horse programs

What’s a connection? When a client makes a proper request of a server (using the proper port number), these two machines may establish a connection –allows them to communicate with one another java.net.Socket : Java class for a basic connection –How many sockets are needed? 2 Socket s, one for each side

So what’s really happening? For a client/server architecture to work, the client must know: –the server’s hostname –the appropriate server application’s port number CLIENT 1)Constructs a Socket that tries to connect to the server 3)Uses the socket to send data to the server SERVER 2)Accepts connection and gets a socket bound to a different port to send data to the client.

Are you with me? Why switch server ports? Java automatically selects the client port and the new server port for you (yay!)

The Socket class Used on both sides (client & server) Constructor: –Socket(String host, int port) Creates a stream socket HAS-A InputStream –used to get data sent by other side –getInputStream() HAS-A OutputStream –used to send data to other side –getOutputStream()

What good is an InputStream or OutputStream ? No good by themselves We have to attach them to more useful readers and writers Options: –Text: BufferedReader & PrintWriter –Bytes: ByteArrayInputStream & ByteArrayOutputStream –Objects: ObjectInputStream & ObjectOutputStream

Example: Reverse Client/Server Create a client/server pair whereby: –the server name is sparky.ic.sunysb.edu –the server program listens on port 6000 –once a client connects, any text sent to the server will be returned in reverse order –only one client may connect for the duration of the server (how pitiful) What do we need? –2 applications 1 runs on the server (ReverseEchoServer.java) 1 runs on a client (ReverseEchoClient.java)

ReverseEchoClient GUI JTextArea inside a JScrollPane JTextField

public class ReverseEchoServer { public static void main(String[] args) { ServerSocket server; Socket connection; BufferedReader reader; PrintWriter writer; try { server = new ServerSocket(6000); connection = server.accept(); InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); reader = new BufferedReader(isr); OutputStream os = connection.getOutputStream(); writer = new PrintWriter(os); ReverseEchoServer.java

String message = reader.readLine(); while (message != null) { String reverse = ""; for (int i = message.length()-1; i >= 0; i--) reverse += message.charAt(i); writer.println(reverse); writer.flush(); message = reader.readLine(); } } catch (IOException ioe) { ioe.printStackTrace(); } } } ReverseEchoServer.java (continued)

public class ReverseEchoClient extends JFrame implements ActionListener { private JTextArea textArea = new JTextArea(); private JScrollPane jsp = new JScrollPane(textArea); private JTextField textField = new JTextField(); private BufferedReader reader; private PrintWriter writer; public ReverseEchoClient() { super("ReverseEchoClient"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(600,400); this.add(jsp, "Center"); this.add(textField, "South"); textField.addActionListener(this); connect(); } ReverseEchoClient.java

public void connect() { try { String host = "sparky.ic.sunysb.edu"; Socket connection = new Socket(host, 6000); OutputStream os = connection.getOutputStream(); writer = new PrintWriter(os); InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); reader = new BufferedReader(isr); } catch(IOException ioe) { ioe.printStackTrace(); } } ReverseEchoClient.java (continued) How could you test this locally? host = "localhost";

public void actionPerformed(ActionEvent ae) { try { String message = textField.getText(); textField.setText(""); textArea.append("\nClient: " + message); writer.println(message); writer.flush(); String response = reader.readLine(); textArea.append("\nServer: " + response); } catch(IOException ioe) { ioe.printStackTrace(); } } public static void main(String[] args) { ReverseEchoClient frame = new ReverseEchoClient(); frame.setVisible(true); } } ReverseEchoClient.java (continued)

What would happen … to the server if the client connection was broken? –e.g., the client application was closed the readXXX method would throw an IOException to the client if the server connection was broken? –e.g., the server application was closed the readXXX method would throw an IOException These cases will have to be handled, but in different ways (we’ll see later)

What’s a protocol? A standard way for computers to communicate across the internet –Ex: HTTP, FTP, TCP/IP, UDP Why do we care about protocols? –if you are to define a networked client/server program, you have to define the protocol of behavior What will be sent? –Text messages only? –Objects using Object Serialization? (If so what types of objects?) –In what order? –What will each type of message mean?

Object Serialization (I/O sending Objects) ObjectInputStream / ObjectOutputStream, –read and write objects ObjectInputStream –public final Object readObject() throws IOException, ClassNotFoundException ObjectOutputStream –public final void writeObject(Object obj) throws IOException

More on Serializable An object may be read/written only if it is serializable –a object is serializable only if: its class implements the Serializable interface and all ancestors implement Serializable and all instance variables’ classes implement Serializable Serializable interface has no methods

Networking Serialization Hazards 1.Make sure reader is anticipating the same type of object the writer is sending 2.Make sure sent object & all its components implement Serializable 3.Static variables are not sent 4.The same object may only be sent once on a single stream –to send an object repeatedly, it must be clone d 5.For a given Socket, only construct one ObjectOutputStream & one ObjectInputStream 6.When constructing your streams, contruct the ObjectOutputStream first, then the ObjectInputStream Reference: Serialization Gotchas & Strange Behavior (

Network Objects & Protocols Sending Objects is easy Different types of objects may be needed to be sent in a single client/server architecture Construct a class to represent all objects sent, it will include: –data (the actual Objects) –type of object/communications –protocol (possible types of objects/communications) This network object would be used by both clients and servers (like a packet for objects)

Ex: Protocols & Objects Suppose I want to create a client/server pair whereby: –the client may request different types of info from the server echo reversed text (like before) today’s date –What do we need? 3 classes –the protocol & data to be sent (DumbNetworkObject.java) –the server (DumbServer.java) –the client (DumbClient.java)

DumbClient GUI

SERVERCLIENT Wait for Client to send data Wait for user to click on button Wait for Server to send data Determine type of data the user wants What did the client request? Construct appropriate object and send to server Construct appropriate object and send to client How did the server respond? Update GUI

public class DumbNetworkObject implements Serializable { private int type; private Object data = null; public static final int REQUEST_REVERSE = 0; public static final int REQUEST_DATE = 1; public static final int RESPONSE_REVERSE = 2; public static final int RESPONSE_DATE = 3; public DumbNetworkObject(int initType) { type = initType; } public DumbNetworkObject(int initType, Object initData) { data = initData; type = initType; } public Object getData(){ return data; } public int getType() { return type;} } DumbNetworkObject.java

public class DumbServer { public static void main(String[] args) { ServerSocket server; Socket connection; ObjectInputStream reader; ObjectOutputStream writer; try { server = new ServerSocket(7000); connection = server.accept(); OutputStream os = connection.getOutputStream(); writer = new ObjectOutputStream(os); InputStream is = connection.getInputStream(); reader = new ObjectInputStream(is); DumbServer.java

DumbNetworkObject incoming = (DumbNetworkObject)reader.readObject(); while (incoming != null) { DumbNetworkObject outgoing; int request = incoming.getType(); if (request == DumbNetworkObject.REQUEST_REVERSE) { String text = (String)incoming.getData(); String reverse = ""; for (int i = text.length()-1; i >= 0; i--) reverse += text.charAt(i); outgoing = new DumbNetworkObject( DumbNetworkObject.RESPONSE_REVERSE,reverse); writer.writeObject(outgoing); } DumbServer.java (continued)

else if (request == DumbNetworkObject.REQUEST_DATE) { GregorianCalendar today = new GregorianCalendar(); outgoing = new DumbNetworkObject( DumbNetworkObject.RESPONSE_DATE, today); writer.writeObject(outgoing); } incoming = (DumbNetworkObject)reader.readObject(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } catch (IOException ioe) { System.out.println("Client Disconnected - Closing"); System.exit(0); } DumbServer.java (continued)

public class DumbClient extends JFrame implements ActionListener{ private JTextArea textArea = new JTextArea(); private JScrollPane jsp = new JScrollPane(textArea); private JTextField textField = new JTextField(); private JPanel buttonPanel = new JPanel(); private JButton reverseButton = new JButton("Reverse"); private JButton dateButton = new JButton("Date"); private ObjectOutputStream writer; private ObjectInputStream reader; public DumbClient() { super("DumbClient"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(600,400); Container cp = getContentPane(); cp.add(buttonPanel, "North"); cp.add(jsp, "Center"); cp.add(textField, "South"); reverseButton.addActionListener(this); dateButton.addActionListener(this); buttonPanel.add(reverseButton); buttonPanel.add(dateButton); connect(); } DumbClient.java

public void connect() { try { Socket connection = new Socket("localhost", 7000); OutputStream os = connection.getOutputStream(); writer = new ObjectOutputStream(os); InputStream is = connection.getInputStream(); reader = new ObjectInputStream(is); } catch(IOException ioe) { ioe.printStackTrace(); } } DumbClient.java (continued)

public void actionPerformed(ActionEvent ae) { String command = ae.getActionCommand(); DumbNetworkObject outgoing; try { if (command.equals("Reverse")) { String message = textField.getText(); textField.setText(""); textArea.append("\nClient: " + message); outgoing = new DumbNetworkObject( DumbNetworkObject.REQUEST_REVERSE, message); writer.writeObject(outgoing); } else if (command.equals("Date")) { outgoing = new DumbNetworkObject( DumbNetworkObject.REQUEST_DATE); writer.writeObject(outgoing); } writer.flush(); handleResponse(); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } catch(IOException ioe) { JOptionPane.showMessageDialog(this,"Server Disconnected - Closing"); System.exit(0); } DumbClient.java (continued)

public void handleResponse() throws IOException, ClassNotFoundException { DumbNetworkObject dno = (DumbNetworkObject)reader.readObject(); int response = dno.getType(); if (response == DumbNetworkObject.RESPONSE_REVERSE) { String reverse = (String)dno.getData(); textArea.append("\nServer: " + reverse); } else if (response == DumbNetworkObject.RESPONSE_DATE) { Calendar date = (GregorianCalendar)dno.getData(); textArea.append("\nServer: today's date is " + (date.get(Calendar.MONTH)+1) + " " + (date.get(Calendar.DATE)) + ", " + (date.get(Calendar.YEAR))); } public static void main(String[] args) { DumbClient frame = new DumbClient(); frame.setVisible(true); } DumbClient.java (continued)

Asynchronous Communications? Do our servers so far permit multiple connections? –NO! –to do this we’ll need multi-threading, ex: while (true) { accept a connection ; create a thread to deal with the client ; } Do our clients so far allow for communications from the server at any time? –NO! –to do this we’ll need multi-threading –right now, the client only gets messages from the server immediately after sending one.

At Home Exercise Do ASAP Run the TicTacToe program provided on the schedule page –do so ASAP –this is a networked, two player Tic Tac Toe –by the end of this week you should intimately understand every single line of code less than 400 in all To play: –run the TicTacToeServer application –run two TicTacToeClient applications

Turn-Based Game Network Architecture Game Server Client Player 1Client Player 2 Also called “Star” topology Useful for slow-paced games (like board games) Not useful for fast-paced, graphics intensive games –Also called “mesh” & “interconnect” topology –use multicast connections ( MulticastSocket class)

Star vs. Mesh Topologies (Ref: Star Topology –All devices are connected to a central hub (server) –Nodes communicate across the network by passing data through the hub Mesh Topology –every node has a connection to every other node in the network. –provides faster communication –burden on clients to enforce application rules –minimize size of messages