Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSPP51037 – Advanced Java Lesson 1 Introduction/Warmup Java Socket Programming.

Similar presentations

Presentation on theme: "CSPP51037 – Advanced Java Lesson 1 Introduction/Warmup Java Socket Programming."— Presentation transcript:

1 CSPP51037 – Advanced Java Lesson 1 Introduction/Warmup Java Socket Programming

2 Policies  Grade based on 3 large programming assignments + final | in-class quizzes.  You must write your own code for all assignments. The consequences for cheating are severe.  There will be a 3-day 10% penalty grace period for each assignment. After that, assignments will not be accepted.  Attendance is not required.  No auditors unless pre-approved!

3 Comments on course Topics  Will follow Volume 2 of Core Java fairly closely.  This includes many topics in distributed programming – socket programming, URL classes, RMI, servlets, web services, JMS  Other advanced java features – JDBC, graphics programming, advanced multithreading, JNI  Things not covered in depth – EJB, CORBA, JSP  It is assumed that you know Horstmann Volume I  Detailed web page maintained througout course

4 Java Socket Classes

5 What is a socket?  Generally refers to a stream connecting processes running in different address spaces (across a network or on the same machine).  We say “create a socket connection between machine A and machine B”. This means, roughly, create input and output streams for sending data between programs running simultaneously on each machine.  The programs can then “talk to each other”.  This is lowest-level form of communication from application developer’s view

6 Sockets, cont.  Sockets represent a low-level abstraction for application communication. –Programmer is aware of a stream that connects two computers. –Programmer fully responible for managing/interpreting flow of bytes between computers  Higher-level techniques –message passing systems (MPI, SOAP, JMS), extensions to web servers (ASP, JSP, servelets, etc), distributed objects (CORBA, RMI), web services, etc.

7 More about sockets in Java  One of the good things about Java  Supported natively by the standard languages (j2sdk)  Distinction between high and low-level blurred somewhat by ability to wrap streams (ObjectOutputStream, etc.)  Still, socket programming differs from other distributed programming in its low-level nature.

8 Why is this paradigm useful?  Shared resources (web servers, ftp servers, mail servers)  Online auctions, exchanges, etc.  Data locality  Localize computing power  Crash protection  Software maintainability

9 Conceptual overview of basic client-server program  Write a program that dials up another program at a specified IP address running on a specified port. Call this program the client.  Second program (server) accepts connection and establishes input/output stream to client.  When server accepts, client can establish input/ouput stream to server  Client makes request of server by sending data. Server sends replies to client. Protocol must be defined so client/server understand can interpret messages.

10 Conceptual overview of basic peer-to-peer program  Two processes running on specific port of specific machine.  Either process can dial up the other process.  When connection is established, applications talk at a peer level, rather than one making requests and the other serving up those requests.  Will see many examples soon.

11 Socket Machinery in Java

12 Java classes for direct socket programming  Good news: This is very simple in Java  Really only 3 additional classes are needed   

13 Most important classes/methods  –Socket(InetAddress addr, int port); create a Socket connection to address addr on port port –InputStream getInputStream(); returns an instance of InputStream for getting info from the implicit Socket object –OutputStream getOutputStream(); returns an instance of OutputStream for sending info to implicit Socket object. –close(); close connection to implicit socket object, cleaning up resources.

14 Important classes, cont.  –ServerSocket(int port); enables program to listen for connections on port port –Socket accept(); blocks until connection is requested via Socket request from some other process. When connection is established, an instance of Socket is returned for establishing communication streams.

15 Important class, cont.  –static InetAddress getByName(String name) given a hostname name, return the InetAddress object representing that name (basically encapsulates name and IP associated with name); –static InetAddress[] getAllByName(String name) same as above but for case where many ip’s mapped to single name (try, e.g.) –static InetAddress getLocalHost() get InetAddress object associated with local host. –static InetAddress getByAddress(byte[] addr) get InetAddress object associated with address addr

16 Error Handling  Very important to ensure that server is robust and will not crash.  Important Exceptions: –InterruptedIOException –ConnectException  Be sure to close your sockets either after a crash or upon expected completion. Finally clause is useful here.

17 Examples  Best way to learn this is to study several canonical examples  See many simple course examples under standaloneClient package  Next, do simple EchoServer  Then, Threaded EchoServer  Then, fully synchronized tic-tac-toe  Then, chess game

18 Messages/Protocols

19 What is a message?  Technically, a structured piece of info sent from one agent to another.  Can be thought of as a set of commands with arguments that each agent understands and knows how to act upon.  Groupings of such commands are commonly referred to as a “protocol”.  HTTP, FTP, etc. are all protocols (get, put,...)

20 Why write our own message- passing system?  Existing protocols might be totally inappropriate for the needs of an application.  An existing protocol may work but be too inefficient (e.g. SOAP).  In general, can fine-tune the protocol exactly to your application to minimize memory and bandwitdth overhead.

21 What about distributed objects?  Can be overkill when communication needs are simple.  Can be inefficient when transaction throughput is critical.  Rapid implementation takes precedence of sophisitication/flexibility  special network protocols need to be avoided (behind a firewall, etc.)  CORBA, RMI, etc. not available

22 Architecting a Message Passing System  Crucial point: –Isolate communication details from application details. This is what we will discuss today. Your stand-alone objects should be well- defined and unaware of the message passing environment. –Provide a structured way to link messages to method calls on these objects.

23 Asynchronous vs. Synchronous Message Handling  Synchronous: each agent waits for response after sending their message, then does work – “handshaking”.  Aysnchronous (typical) – work needs to be done after sending message. Doesn’t know when reply will come, but single thread busy so can’t process message.

24 Simple Chess Framework  We will illustrate some of these concepts by creating the framework for a two-person game of chess.  I say “framework” because the entire class structure and all methods are in place. However, the implementations of the methods are left incomplete. The hard work has been done, though, and what remains is totally isolated and algorithmic.

25 Base classes  We start with two abstract base classes: public abstract class BasicMessage{ protected String id; //”command” protected Vector argList;//”arguments” //accessors/mutators go here public abstract boolean Do(); }  When a message is received by an agent, the Do method is called to perform the appropriate action. Individual messages that subclass BasicMessage must implement this method.

26 BasicMsgHandler  Some comments on the BasicMsgHandler: –Stores the input and output streams for reading and writing, wherever these come from. –readMsg “marshals” raw data and builds BasicMessage object – uses buildMessage(). –sendMsg “unmarshals” BasicMessage object and sends raw data tokens to stream. –run reads a message and processes (Do method) when something is in the input stream.

27 Base Classes, cont.  The second is a basic handler with support for both synchronous and asynchronous messages: public abstract class BasicMsgHandler implements Runnable{ InputStream in; OutputStream out; //constructors, accessor/mutators public BasicMessage readMsg() throws IOException; public void send Msg(BasicMessage) throws IOException; public void run(){} //calls readMsg continuously and processes protected abstract BasicMessage buildMessage(String) ; //creates object

28 BasicMsgHandler  Contains functionality to do the following: –marshal and unmarshal message tokens to/from BasicMessage objects. –read a message synchronously –send a message –read messages asychronously and call Do method to perform action associated with message.

29 Source code links  

30 Creating the local objects  At this point we’ll step aside from the networking aspect and create the local, standalone ChessPlayer class.  The important point is that this class should have no knowledge that it will live in a networked environment. This division of labor greatly facilitates code maintenance, testing, and reuse.

31 ChessPlayer class public class ChessPlayer{ //constructors //gets the next move (by reference) public boolean nextMove(String from, String to, int mate); //called as attempt by other player to move. accept or reject public boolean acceptMove(String from, String to, int mate); //called after other player’s acceptMove returns true public void moveAccepted(String from, String to, int mate); //called when other player quits public void conceded(); }

Download ppt "CSPP51037 – Advanced Java Lesson 1 Introduction/Warmup Java Socket Programming."

Similar presentations

Ads by Google