Presentation is loading. Please wait.

Presentation is loading. Please wait.

Network Programming Introduction

Similar presentations


Presentation on theme: "Network Programming Introduction"— Presentation transcript:

1 Network Programming Introduction
Based on Classes in the java.net package Lecture focuses on: TCP and UDP Network programming basics Identifying a machine Servers and Clients Ports and sockets Data transfer using sockets

2 TCP and UDP Lots of java programs use Transmission Control Protocol (TCP) Connection-based (where java stream sockets provides continuous data stream), reliable, data streams will always get there. Also high overhead. We will focus on TCP/IP sockets. User Datagram Protocol (UDP) is not connection-based (connectionless service with datagram sockets allowing one message, an unreliable protocol which is much faster, but the message won’t always get there

3 Network Programming Basics
The classes in java.net: Java programs can use TCP or UDP to communicate over the Internet. The URL, URLConnection (for Web applications), Socket, and ServerSocket (client-server applications) classes all use TCP to communicate over the network. The DatagramPacket, DatagramSocket, and MulticastSocket classes are for use with UDP.

4 Network Programming Basics
Historically error-prone, difficult, complex JAVA has complete network package, java.net I/O stream library works quite well for TCP/IP Threading is also very useful and relatively easy here

5 Identifying a Machine Uniquely identify a machine from all the others in the world IP (Internet Protocol) address that can exist in two forms:

6 Identify a Machine (Continue)
DNS(Domain Name Service) form java.sun.com “Dotted quad” form: static InetAddress.getByName() produces java object containing address

7 Servers and Clients Two machines must connect
Server waits for connection Client initiates connection (create socket) Once the connection is made, server & client look identical

8 Testing w/o a network For testing your program, you can do it w/o network. (server & client on same machine) Localhost: the IP address for testing without a network Three ways to identify:

9 Test w/o networking (Continue)
InetAddress addr=InetAddress.getByName(null); Equivalently: InetAddress.getByName(“localhost”); Or using the reserved IP number for the loopback: InetAddress.getByName(“ ”);

10 Port number IP address isn’t enough to identify a unique server
many servers can exist on one machine port number: Unique in a Machine Not a physical location, but a software abstraction to represent a service

11 Port number (Continue)
When set up client and server, you must specify IP address and port. Port number range: 0 to 65,535 are reserved, others may be used.

12 Sockets Software abstraction used to represent the connection between two machines Socket is the actual 2-way connector.

13 Sockets The following sequence establishes a socket from the client class InetAddress addr = InetAddress.getByName(null); Socket socket = new Socket(addr, 8080);

14 Sockets At the server class, the following establishes the server port, and waits for a client request to establish a socket ServerSocket s = new ServerSocket(8080); Socket socket = s.accept();

15 Data transfer using sockets
Once you have a Socket, you call getInputStream() and getOutputStream() to produce the corresponding InputStream and OutputStream objects You can convert these to readers and writers, wrap them in a BufferedReader or BufferedWriter and PrintWriter

16 Data transfer using sockets (continue)
At the server and client classes BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream())); PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())),true);

17 Data transfer using sockets (continue)
From then on, it’s like reading and writing any other I/O stream! while (true) { String str = in.readLine(); if (str.equals("END")) break; System.out.println("Echoing: " + str); out.println(str); } Example: JabberClient JabberServer

18 UDP Sockets Since UDP is a connectionless protocol; there is no virtual stream between the hosts so streams are not used for IO. UDP applications are not thought of in terms of clients and servers, but rather in terms of senders and receivers. For conversational applications both ends (sender and receiver) will be changing states from sender to receiver and back again Many UDP based applications are simple send a request then receive the data (sender’s perspective), like a DNS request. The receiver’s perspective is to ‘listen’ for a request, send the response, listen for more requests.

19 DatagramPacket Class UDP sockets send and receive Datagrams
Constructors: two for receiving, four for sending DatagramPacket( byte[ ] buff , int len) Constructs a DatagramPacket for receiving packets of length len. DatagramPacket(byte[] buf, int off, int len) Constructs a DatagramPacket for receiving packets of length len, specifying an offset of off bytes into the buffer. DatagramPacket((byte[] buf, int len, InetAddress addr, int port) Constructs a datagram packet for sending packets of length len to the specified port number on the specified host. DatagramPacker(byte[] buf, int off, int len, InetAddress addr, int port) Constructs a datagram packet for sending packets of length len with offset off to the specified port number on the specified host. DatagramPacket(byte[] buf, int off, int len, SocketAddress addr)

20 DatagramPacket Class DatagramPacket(byte[] buf, int len, SocketAddress addr) Constructs a datagram packet for sending packets of length len to the specified port number on the specified host. Getter methods getAddress( ) getData( ) getLength( ) getOffset( ) getPort( ) getSocketAddress( ) Setter methods setAddress(InetAddress iaddr) setData(byte[ ] buf) setData(byte[] buf, int offset, int length) setLength(int len) setPort(int port) setSocketAddress(SocketAddress saddr)

21 DatagramSocket Class – UDP Sockets
Constructors DatagramSocket() Constructs a datagram socket and binds it to any available port on the local host. DatagramSocket(DatagramSocketImpl impl) Creates an unbound datagram socket with the specified DatagramSocketImpl. DatagramSocket(int port) Constructs a datagram socket and binds it to the specified port on the local host. DatagramSocket(int port, InetAddress iaddr) Creates a datagram socket, bound to the specified local address. DatagramSocket(SocketAddress bindaddr)  Creates a datagram socket, bound to the specified local socket address.

22 DatagramSocket Class – operational Methods
Operational (void) Methods bind(SocketAddress  addr) connect(InetAddress address, int port) connect(SocketAddress addr) disconnect( ) receive(DatagramPacket p) send(DatagramPacket p) close( )

23 DatagramSocket Class – getter methods
DatagramChannel getChannel( ) InetAddress getInetAddress( ) boolean getBroadcast( ) InetAddress getLocalAddress( ) int getLocalPort( ) SocketAddress getLocalSocketAddress( ) SocketAddress getRemoteSocketAddress( ) int getPort( ) int getReceiveBufferSize( ) int getSendBufferSize( ) boolean getReuseAddress( ) int getSoTimeout( ) int getTrafficClass( )

24 DatagramSocket Class – setter methods
void setBroadcast( boolean on) static void setDatagramSocketImplFactory (DatagramSocketImplFactory fac) void serReceiveBufferSize(int size) void setReuseAddress(boolean on) void setSevdBufferSize(int size) void setSoTimeout(int timeout) void setTrafficClass(int tc)

25 DatagramSocket Class – test methods
boolean isBound( ) boolean isClosed( ) boolean isConnected( )

26 URL Class - Constructors
URL(String spec) Creates a URL object from the String representation. URL(String protocol, String host, int port, String file)  Creates a URL object from the specified protocol, host, port number, and file. URL(String protocol, String host, int port, String file, URLStreamHandler handler)   Creates a URL object from the specified protocol, host, port number, file, and handler. URL(String protocol, String host, String file) Creates a URL from the specified protocol name, host name, and file name. URL(URL context, String spec) Creates a URL by parsing the given spec within a specified context URL(URL context, String spec, URLStreamHandler handler)  Creates a URL by parsing the given spec with the specified handler within a specified context.

27 URL Class - Methods Getters String getAuthority( )
Object getContent( ) Object getContent(Classes[ ] classes) int getDefaultPort( ) String getFile( ) String getHost( ) String getPath( ) int getPort( ) String getProtocol( ) String getQuery( ) String getRef( ) String getUserInfo( )

28 URL Class - Methods Setters
set(String protocol, String host, int port, String file, String ref) set(String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref) setURLStreamHandlerFactory(URLStreamHandlerFactory fac)

29 URL Class – Utility methods
int hashCode( ) URLConnection openConnection( ) InputStream openStream( ) boolean sameFile(URL other) String toExternalForm( ) String toString( ) boolean equals(Object obj)

30 Multiple Client - Server Chat Programming
Sockets Programming in Java What is a socket ? A socket is the one end-point of a two-way communication link between two programs running over the network.

31 How a network connection is created ?
A network connection is initiated by a client program when it creates a socket for the communication with the server. To create the socket in Java, the client calls the Socket constructor and passes the server address and the the specific server port number to it. At this stage the server must be started on the machine having the specified address and listening for connections on its specific port number. The server uses a specific port dedicated only to listening for connection requests from clients. It can not use this specific port for data communication with the clients because the server must be able to accept the client connection at any instant. So, its specific port is dedicated only to listening for new connection requests. The server side socket associated with specific port is called server socket. When a connection request arrives on this socket from the client side, the client and the server establish a connection.

32 This connection is established as follows:
When the server receives a connection request on its specific server port, it creates a new socket for it and binds a port number to it. It sends the new port number to the client to inform it that the connection is established. The server goes on now by listening on two ports: it waits for new incoming connection requests on its specific port, and it reads and writes messages on established connection (on new port) with the accepted client.

33 how to program TCP based client/server applications.
Opening a socket The client side When programming a client, a socket must be opened like below: Socket MyClient; try { MyClient = new Socket("MachineName", PortNumber); } catch (IOException e) { System.out.println(e); }

34 The server side When programming a server, a server socket must be created first, like below: ServerSocket MyService; try { MyServerice = new ServerSocket(PortNumber); } catch (IOException e) { System.out.println(e); }

35 The server socket is dedicated to listen to and accept connections from clients. After accepting a request from a client the server creates a client socket to communicate (to send/receive data) with the client, like below : Socket clientSocket = null; try { serviceSocket = MyService.accept(); } catch (IOException e) { System.out.println(e); }

36 Creating an input stream
On the client side, you can use the DataInputStream class to create an input stream to receive responses from the server: DataInputStream input; try { input = new DataInputStream(MyClient.getInputStream()); } catch (IOException e) { System.out.println(e); }

37 DataInputStream input;
On the server side, the DataInputStream is used to receive inputs from the client: DataInputStream input; try { input = new DataInputStream(serviceSocket.getInputStream()); } catch (IOException e) { System.out.println(e); }

38 Create an output stream
On the client side, an output stream must be created to send the data to the server socket using the classPrintStream or DataOutputStream of java.io package: PrintStream output; try { output = new PrintStream(MyClient.getOutputStream()); } catch (IOException e) { System.out.println(e); }

39 Also, one may want to use the DataOutputStream:
DataOutputStream output; try { output = new DataOutputStream(MyClient.getOutputStream()); } catch (IOException e) { System.out.println(e); }

40 On the server side, one can use the class PrintStream to send data to the client.
PrintStream output; try { output = new PrintStream(serviceSocket.getOutputStream()); } catch (IOException e) { System.out.println(e); }

41 Closing sockets On the client side you have to close the input and the output streams and the socket like below: try { output.close(); input.close(); MyClient.close(); } catch (IOException e) { System.out.println(e); }

42 On the server you have to close the input and output streams and the two sockets as follows:
try { output.close(); input.close(); serviceSocket.close(); MyService.close(); } catch (IOException e) { System.out.println(e); }


Download ppt "Network Programming Introduction"

Similar presentations


Ads by Google