cse 219 computer science iii network programming (application layer) reference:...

40
CSE 219 Computer Science III Network Programming (Application Layer) Reference: http://java.sun.com/docs/books/tutorial/net working/

Upload: maude-quinn

Post on 29-Dec-2015

232 views

Category:

Documents


0 download

TRANSCRIPT

CSE 219Computer Science III

Network Programming(Application Layer)

Reference: http://java.sun.com/docs/books/tutorial/networking/

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: 129.49.1.3)

• like a phone number for computers on the Net• anyone know the local IP address?

– 127.0.0.1

– 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:• http://www.hcidata.co.uk/host2ip.htm

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 65536 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: http://www.iana.org/assignments/port-numbers

• 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 Sockets, 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 Hazards1. Make sure reader is anticipating the same type of object the

writer is sending2. Make sure sent object & all its components implement

Serializable3. Static variables are not sent4. The same object may only be sent once on a single stream

– to send an object repeatedly, it must be cloned

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 (http://www.churchillobjects.com/c/11009e.html)

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

SERVER CLIENT

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 1 Client 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: http://www.webopedia.com/quick_ref/topologies.asp)

• 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