Java.net CS-328 Dick Steflik.

Slides:



Advertisements
Similar presentations
Socket UDP H. Fauconnier 1-1 M2-Internet Java. UDP H. Fauconnier M2-Internet Java 2.
Advertisements

Referring to Java API Specifications
UDP Datagrams and Sockets Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung University.
Jan Java Networking UDP Yangjun Chen Dept. Business Computing University of Winnipeg.
Programming TCP Clients Version InetAddress Class An IP address identifies uniquely a host in the internet, which consists of 4 numbers (1 byte.
Prepared By E. Musa Alyaman1 Java Network Programming TCP.
Prepared By E. Musa Alyaman1 URLs, InetAddresses, and URLConnections Chapter 9.
User Datagram Protocol. Introduction UDP is a connectionless transport protocol, i.e. it doesn't guarantee either packet delivery or that packets arrive.
Prepared By E. Musa Alyaman1 User Datagram Protocol (UDP) Chapter 5.
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 L53 Networking (2). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
Networking Support In Java 2 Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Internet Programming In Java. References Java.sun.com Java552 Many of the programs shown.
Lecture 11 Java Socket Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger and Joonbok Lee.
Networking Support In Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Networking Support In Java 2 Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
13-Jul-15 Sockets and URLs. 2 Sockets A socket is a low-level software device for connecting two computers together Sockets can also be used to connect.
Networking java.net package, which provides support for networking. Its creators have called Java “programming for the Internet.” Socket :- A network socket.
Networking in Java Representation and Management of Data on the Internet.
Java Networking.
Socket Programming -What is it ? -Why bother ?. Basic Interface for programming networks at transport level It is communication end point Used for inter.
Babak Esfandiari (based on slides by Qusay Mahmoud)
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
Multicast Sockets What is a multicast socket?
Application Protocols: HTTP CSNB534 Semester 2, 2007/2008 Asma Shakil.
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:
DBI Representation and Management of Data on the Internet.
UDP vs TCP UDP Low-level, connectionless No reliability guarantee TCP Connection-oriented Not as efficient as UDP.
Socket Programming in Java CS587x Lecture 4 Department of Computer Science Iowa State University.
1 A TCP/IP Application Programming Perspective Chris Greenhalgh G53ACC.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
Java Sockets Programming
L 2 - 1 3( 1/ 20) : Java Network Programming. The Socket API The previous contents describe client-server interaction that application programs use when.
What is a Network? Computer network Computer network a set of computers using common protocols to communicate over connecting transmission media. a set.
Sockets For Clients Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung University.
Java Networking. java.net package provides support of networking. Its creators have called Java "programming for the Internet." What makes Java a good.
Networking Java (2/3)
Java IO. Why IO ? Without I/O, your program is a closed box. Without I/O, your program is a closed box. I/O gives your Java program access to your hard.
CSI 3125, Preliminaries, page 1 Networking. CSI 3125, Preliminaries, page 2 Inetaddress Class When establishing a connection across the Internet, addresses.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
Java Programming II Java Network (I) Java Programming II.
Distributed Systems CS Project 1: File Storage and Access Kit (FileStack) Recitation 1, Aug 29, 2013 Dania Abed Rabbou and Mohammad Hammoud.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
UDP User Datagram Protocol. About the UDP A commonly used transport protocol Does not guarantee either packet delivery or order The packets may travel.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
UDP Programming. Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2007 2/86 Overview.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
Network Programming. These days almost all devices.
Network Programming Communication between processes Many approaches:
Object-Orientated Analysis, Design and Programming
Secure Sockets SSL (Secure Sockets Layer) is a standard security technology for establishing an encrypted link between a server and a client—typically.
Source: Java Sockets Source:
Network Programming Introduction
NETWORK PROGRAMMING CNET 441
An Introduction to TCP/IP and Sockets
PRESENTED To: Sir Abid………. PRESENTED BY: Insharah khan………. SUBJECT:
Network Programming Introduction
Network Programming Introduction
Sockets and URLs 17-Sep-18.
Java Network Programming
Sockets and URLs 13-Nov-18.
UNIT-6.
URL in Java C343 Lab (Week 13).
Networking.
Sockets and URLs 3-Dec-18.
Networking.
NETWORK PROGRAMMING CNET 441
Java Socket Programming
Programming TCP Clients
Presentation transcript:

java.net CS-328 Dick Steflik

InetAddress Class The Inetaddress class provides you with a limited interface to DNS for doing both forward and reverse internet address lookups An InetAddress class method corresponds to a DNS request

InetAddress Class No public constructor Three static methods: InetAddress getByName(String) Static method used to retrieve the address for the host name passed as the parameter. InetAddress [ ] getAllByName(String) Static method used to retrieve all the addresses for the host name passed as a parameter. InetAddress getLocalHost( ) Static method used to retrieve the address for the current, or local, host.

InetAddress Class Three additional “getter” methods String getHostName( ) Returns the host name. byte[ ] getAddress( ) Returns the IP address. String getHostAddress( ) Returns the IP address as a string.

InetAddress Examples try { InetAddress fullname = netAddress.getByName(“bigyellowcat.cs.binghamton.edu"); InetAddress alias = InetAddress.getByName(“bigyellowcat"); InetAddress octets = InetAddress.getByName(“128.226.121.44"); if (fullname.equals(alias) && fullname.equals(octets)) // All is right with the world! } catch (UnknownHostException e) { // Exception handling here. }

TCP Sockets Once a TCP socket connection is made, a virtual stream is in place. Java’s IO model is that of a stream, therefore the models are consistent; all you need to do connect a TCP socket to a stream and read and write the streams as normal

Socket Class - TCP Client sockets Socket(String ip, int port) Creates a streaming socket and binds it to the host and port specified as parameters. Socket(String ip, int port, boolean TCPorUDP) Creates a socket and binds it to the host and port specified as parameters. The last parameter is used to indicate whether the socket should be a stream or datagram socket. Socket(InetAddress ia, int port) Creates a streaming socket connected to the specified host and port. Socket(InetAddress ia, int port, boolean TCPorUDP) Creates a socket connected to the specified host and port. The last parameter specifies whether the socket should be a stream or datagram socket.

Client Sockets InetAddress getInetAddress( ) Int getPort( ) Returns an InetAddress object representing the host for this socket. Int getPort( ) . Returns the port number on the remote host for this socket Int getLocalPort( ) Returns the port number on the local host for this socket. InputStream getInputStream( ) Returns an input stream for the socket. OutputStream getOutputStream( ) Returns an output stream for the socket. Close( ) Closes the socket. SetSocketImplFactory (SocketImplFactory) Sets the socket factory that will be used to create all sockets.

Reading and Writing try { Socket socket = new Socket("somehost.somewhere.com", -1); // Always a good idea to buffer the stream to mitigate blocking. PrintStream out = new PrintStream( new BufferedOutputStream(socket.getOutputStream())); out.println("Are you listening?"); DataInputStream in = new DataInputStream( new BufferedInputStream(socket.getInputStream())); in.readLine(); // ... // Don't forget to close the socket! socket.close() } catch (Exception e) // Exception handling logic.

Examples See DayTimeClient and EchoClient on web site

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.

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)

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)

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.

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( )

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( )

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)

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

Datagram Sockets Examples See examples on web site

URL Class RFC 2396 essentially a “pointer” to a resource on the World Wide Web different services use slightly different formats file://ftp.yoyodyne.com/pub/files/foobar.txt http://www.yahoo.com/index.html ftp://useracct@someftpserver.com news:rec.gardening gopher://gopher.banzai.edu:1234/

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.

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( )

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)

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

URL Class - example see ReadURL example on web site

ServerSocket Used as the main connection point for some service you wish to provide. Once created, it listens for connection requests then queues the request for disposition On Unix/Linux you must be root to use

ServerSocket – Life cycle A new ServerSocket is created on a particular port using a ServerSocket( ) constructor. The ServerSocket listens for incoming connection attempts on that port using its accept( ) method. accept( ) blocks until a client attempts to make a connection, at which point accept( ) returns a Socket object connecting the client and the server. Depending on the type of server, either the Socket's getInputStream( ) method, getOutputStream( ) method, or both are called to get input and output streams that communicate with the client. The server and the client interact according to an agreed-upon protocol until it is time to close the connection. The server, the client, or both close the connection. The server returns to step 2 and waits for the next connection.

ServerSockets - threads Simultaneous requests are held in a queue, as each request is removed from the queue and processed new connections requests can be added to the queue. Connection requests received while the queue is full will be blocked. Some clients use multiple retries in this case as queue space will usually open up pretty quickly. For simple protocols (DayTime) the queue can usually handle all of the requests without problem For more complex protocols (HTTP) use a thread to process each connection. Threads have less overhead than spawning an entire child process.

ServerSocket - Constructors public ServerSocket(int port) throws IOException, BindException public ServerSocket(int port, int queueLength) throws IOException, BindException public ServerSocket(int port, int queueLength, InetAddress bindAddress) throws IOException

ServerSocket – methods accept( ) – accepts a connection request and creates a socket to the remote user close( ) – close the server socket and wait for next connection request

ServerSocket - example ServerSocket server = new ServerSocket(5776); while (true) { Socket connection = server.accept( ); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream( )); out.write("You've connected to this server. Bye-bye now.\r\n"); connection.close( ); }

Server Sockets - problems You are not root Port is already in use