Socket Programming Using JAVA Asma Shakil Semester 1, 2008/2009.

Slides:



Advertisements
Similar presentations
Umut Girit  One of the core members of the Internet Protocol Suite, the set of network protocols used for the Internet. With UDP, computer.
Advertisements

CCNA – Network Fundamentals
Intermediate TCP/IP TCP Operation.
Chapter 7: Transport Layer
© Janice Regan, CMPT 128, CMPT 371 Data Communications and Networking Socket Programming 0.
1 Chapter 6 Datagram Delivery by UDP Just as the Internet Protocol uses the services of subnetworks, transport protocols build upon the services of IP.
Prepared By E. Musa Alyaman1 Java Network Programming TCP.
Basic Socket Programming with Java. What is a socket?  Generally refers to a stream connecting processes running in different address spaces (across.
Socket Programming.
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
Java Socket Support Presentation by: Lijun Yuan Course Number: cs616.
CS3771 Today: network programming with sockets  Previous class: network structures, protocols  Next: network programming Sockets (low-level API) TODAY!
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L22 (Chapter 25) Networking.
Networking Support In Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
WXES2106 Network Technology Semester /2005 Chapter 8 Intermediate TCP CCNA2: Module 10.
Client Server Model and Software Design TCP/IP allows a programmer to establish communication between two application and to pass data back and forth.
I NTRODUCTION OF S OCKET P ROGRAMMING L.Aseel AlTurki King Saud University.
Gursharan Singh Tatla Transport Layer 16-May
Process-to-Process Delivery:
Greg Jernegan Brandon Simmons. The Beginning…  The problem Huge demand for internet enabled applications and programs that communicate over a network.
Socket Programming -What is it ? -Why bother ?. Basic Interface for programming networks at transport level It is communication end point Used for inter.
1 Transport Layer Computer Networks. 2 Where are we?
Chapter 17 Networking Dave Bremer Otago Polytechnic, N.Z. ©2008, Prentice Hall Operating Systems: Internals and Design Principles, 6/E William Stallings.
NET0183 Networks and Communications Lecture 31 The Socket API 8/25/20091 NET0183 Networks and Communications by Dr Andy Brooks Lecture powerpoints from.
1 Chapter Client-Server Interaction. 2 Functionality  Transport layer and layers below  Basic communication  Reliability  Application layer.
IP and Errors IP Best Effort Datagrams can be: –Lost –Delayed –Duplicated –Delivered out of order –Corrupted.
 Socket  The combination of an IP address and a port number. (RFC 793 original TCP specification)  The name of the Berkeley-derived application programming.
6.1. Transport Control Protocol (TCP) It is the most widely used transport protocol in the world. Provides reliable end to end connection between two hosts.
 TCP (Transport Control Protocol) is a connection-oriented protocol that provides a reliable flow of data between two computers.  TCP/IP Stack Application.
RGEC MEERUT(IWT CS703) 1 Java Networking RGEC Meerut.
The Transmission Control Protocol (TCP) Application Services (Telnet, FTP, , WWW) Reliable Stream Transport (TCP) Connectionless Packet Delivery.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
1. I NTRODUCTION TO N ETWORKS Network programming is surprisingly easy in Java ◦ Most of the classes relevant to network programming are in the java.net.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
Chapter 2 Applications and Layered Architectures Sockets.
The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.
The Socket Interface Chapter 22. Introduction This chapter reviews one example of an Application Program Interface (API) which is the interface between.
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 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.
Sockets For Clients Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung University.
1 Client-Server Interaction. 2 Functionality Transport layer and layers below –Basic communication –Reliability Application layer –Abstractions Files.
Part 4: Network Applications Client-server interaction, example applications.
Socket Programming.
Advanced UNIX programming Fall 2002, lecture 16 Instructor: Ashok Srinivasan Acknowledgements: The syllabus and power point presentations are modified.
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.
Java Programming II Java Network (I) Java Programming II.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
4343 X2 – The Transport Layer Tanenbaum Ch.6.
1 Kyung Hee University Chapter 11 User Datagram Protocol.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
TCP/IP1 Address Resolution Protocol Internet uses IP address to recognize a computer. But IP address needs to be translated to physical address (NIC).
1 Network Communications A Brief Introduction. 2 Network Communications.
Client/Server Design Issues Based on Java Network Programming and Distributed Computing, Chapter 6 Also Online Java Tutorial, Sun.
Network Programming. These days almost all devices.
Chapter 7: Transport Layer
Object-Orientated Analysis, Design and Programming
Chapter 11 User Datagram Protocol
The Transport Layer Implementation Services Functions Protocols
Chapter 9: Transport Layer
Instructor Materials Chapter 9: Transport Layer
MCA – 405 Elective –I (A) Java Programming & Technology
NETWORK PROGRAMMING CNET 441
Process-to-Process Delivery:
Process-to-Process Delivery: UDP, TCP
Presentation transcript:

Socket Programming Using JAVA Asma Shakil Semester 1, 2008/2009

BSD Networking History The sockets API originated with the 4.2BSD system, released in 1983 as part of the BSD UNIX operating system by UC Berkeley. It has gone through several enhancement versions. The latest is 4.4BSD Many Unix systems started with some version of the BSD networking code. In recent years, most operating systems have implemented support for it including Windows XP.

So, what is a socket? A mechanism that provides an endpoint for communication. Similar to a telephone. In the same way that we speak into and listen to a phone, applications both send data across a network by writing to a socket, and receive data sent by a remote host by reading from the socket. An application program requests that a socket be created when one is needed, and the system returns a small integer that the application uses to reference the socket.

Typical Steps Required.. Creating a socket Specifying a local address and binding it to the socket Connecting sockets to destination addresses Sending data through a socket Receiving data through a socket

socket() bind() listen() read() accept() write() socket() connect() write() read() Server Client Socket system calls for connection-oriented protocol (such as TCP) Connection establishment Data (request) Data (reply) Blocks until connection From client Process request

socket() bind() recvfrom() sendto() socket() bind() sendto() recvfrom() Server Client Socket system calls for Connectionless protocol (such as UDP) Data (request) Data (reply) Blocks until data recvd from a client Process request requires the address of the server as a parameter returns the n/w addr of the client process

Recap….. UDP A connectionless transport – doesn’t guarantee either packet delivery or packets arrive in sequential order Bytes are grouped together in discrete packets not an ordered sequence of bytes using I/O stream TCP TCP focuses on establishing a network connection through which a stream of bytes may be sent and received

UDP Advantages UDP communication can be more efficient than guaranteed-delivery data streams. If the amount is small and the data is sent frequently, it may make sense to avoid the overhead of guaranteed delivery Overhead to establish connection can be reduced as compared to TCP Real time applications that demand up-to-the- second or better performance maybe the candidates for UDP, since fewer delay due to the error checking and flow control of TCP UDP sockets can receive data from more than one machine.

Advantages of TCP over UDP Automatic Error Control Data transmission is more dependable. TCP has checksum to ensure that the data is not corrupted during the transmission and data packet lost in transit are retransmitted – an acknowledgement Reliability Each datagram packet contains a sequence number that is used to order data. Later packet arriving before earlier packets will be held in a queue until an ordered sequence of data is available

Cont. Ease of Use TCP allows programmers to think in a completely different way. Rather than being packaged into discrete units, the data is instead treated as a continuous stream like the I/O streams, the reader The mechanism is the same whether the developer is writing to a network socket, a communications pipe, a data structure, the user console or a file. This also applies to reading information

Communication between Application Using Ports Both UDP and TCP share the concept of a communication port to distinguish one application from another The port numbers are divided into three ranges: The Well Known Ports are those from 0 through can only be used by system (or root) processes or by programs executed by privileged users. The Registered Ports are those from 1024 through can be used by ordinary user processes or programs executed by ordinary users. The Dynamic and/or Private Ports are those from through

TCP Sockets and Java Java offers support for TCP sockets in the form of two socket classes Java.net.Socket  For client software  TCP sockets can perform a variety of operations:  Establish a connection to a remote host  Send data to a remote host  Receive data from a remote host  Close a connection Java.net.ServerSocket  For server software  This type of socket can perform the following operations:  Bind to a local port  Accept incoming connections from remote hosts  Unbind from a local port

Java.net.Socket Class Represents client socket and is a communication channel between two TCP communication ports belonging to one or two machines TCP sockets can’t communicate with more than two machines. However, if this functionality is required, a client application should establish multiple socket connections

Creating a Socket Under normal circumstances, a socket is connected to a machine and port when it is created If the network is fine, the call to a socket will return as soon as a connection is establish If not, the constructor may block for an indefinite amount of time

Constructors Several constructors are available Protected Socket ( ) – creates an unconnected socket using the default implementation provided by the current socket factory Socket (InetAddress address, int port) – creates a socket connected to the specified IP address and port Socket (InetAddress address, int port, InetAddress localAddress, int localPort) – creates a socket connected to the specified address and port and is bound to the specified local addressand local port. By default a free port is used but this method allows us to specify a specific port number as well as a specific address, in the case of multihomed hosts (i.e. a machine where the localhost is known by two or more IP addresses)

Cont. Protected Socket (SocketImpl implementation) – creates an unconnected socket using the specified socket implementation. It does not allow a hostname or port to be specified Socket (String host, int port) – creates a socket connected to the specified host and port using string not InetAddress for the hostname Socket ( String host, int port, InetAddress localAddress, int localPort) – creates a socket connected to the specified host and port and bound to the specified local port and address

Example try { //Connect a socket to some host machine and port Socket socket = new Socket(somehost, someport); //create an input stream which reads from the application this socket is connected to. //create an output stream which writes to the application that this socket is connected to. } Catch (Excpetion e) { System.err.println ( “Error – “ + e); }

Reading from and Writing to TCP Sockets Easy process Once a socket is created, it is connected and ready to read/write by using the socket’s input and output streams A filter can be connected to a socket stream to make for simpler programming The functions to do create the input and output streams are as follows: InputStream getInputStream ( ) – returns an input stream, which reads from the application this socket is connected to OutputStream getOutputStream ( ) – returns an output stream, which writes to the application that this socket is connected to

Example try { //Connect a socket to some host machine and port Socket socket = new Socket(somehost, someport); //connect a buffered reader BufferedReader reader = new BufferedReader ( new InputStreamReader ( socket.getInputStream ( ) )); //connect a print stream PrintStream pstream = new PrintStream (socket.getOutputStream( ) ); } Catch (Excpetion e) { System.err.println ( “Error – “ + e); }

Socket Options SO_KEEPALIVE Is used in situations where a client may crash and the end-of-connection sequence is not sent to the TCP server When the keepalive socket option is enabled, the other end of the socket is probed to verify it is still alive. //Enable SO_KEEPALIVE someSocket.setSoKeepAlive(true);

Socket Options SO_RCVBUF Controls the buffer used for receiving data //Modify receive buffer size someSocket.setReceiveBufferSize(4096); SO_SNDBUF Controls the size of the buffer used for sending data //Set the send buffer size to 4096 bytes someSocket.setSendBufferSize(4096);

Socket Options SO_TIMEOUT By default, I/O operations (file- or n/w-based) are blocking in nature. If no data arrives, the application will block indefinitely When the SO_TIMEOUT option is enabled, any read request to the InputStream of a socket starts a timer. If no data is received, the timer expires, a java.io.InterruptedException is thrown, which can be caught to check for a timeout

Example try { //Connect a socket to some host machine and port Socket s = new Socket(somehost, someport); s.setSoTimeout( 5 * 1000); //do some read operation } Catch (InterruptedIOExcpetion iioe) { timeoutFlag = true; // do something; like set a flag } Catch (IOExcpetion ioe) { System.err.println ( “IO Error “ + ioe); System.exit(0); }

Creating a TCP Client A simple TCPEchoClient

ServerSocket Class A special type of socket used to provide TCP service This socket binds to a specific port on the local machine so that the remote machine can locate a service. Client sockets will connect to only one machine Server sockets are capable of fulfilling the request of multiple clients

Creating a ServerSocket Once a server socket is created, it will be bound to a local port and ready to accept incoming connections When clients attempt to connect, they are placed into a queue

Constructors ServerSocket(int port) – binds the server socket to the specified port number, so that clients can locate the TCP service. By default, the queue size is set to 50 ServerSocket (int port, int numberOfClients) – binds the server socket to the specified port number and allocates sufficient space to the queue to support the specified port number of client sockets ServerSocket(int port, int numberOfClient, InetAddress address) – binds the socket to the specified port number and allocates sufficient space to the queue to support the specified port number of client sockets. It also binds a specific IP address in case of multihomed machine

Using a ServerSocket This class provides some basic methods to perform its main duty Methods Socket accept ( ) – waits for a client to request a connection to the server socket and accepts it void close ( ) – closes the server socket, unbinds the TCP port and allows other services to use it InetAddress getInetAddress( ) – returns the address of the server socket

Cont. int getLocalPort ( ) – returns the port number to which the server socket is bound int getSoTimeout ( ) – returns the value of the timeout socket option. If the returned value is 0, the accept operation blocks indefinitely void setSoTimeout (int timeout) – assigns a timeout value for the blocking accept ( ) operation

Accepting and Processing Requests from TCP Clients The most important function of a server socket is to accept client sockets Once a client socket is obtained, the server can perform all the “real work” of server programming

Code Snippet //perform a blocking read operation, to read the //next socket connection Socket nextSocket = someServerSocket.accept () ; //connect a filter reader and writer to the stream BufferedReader reader = new BufferedReader (new InputStreamReader(nextSocket.getInputStream( ) ) ); PrintWriter writer = new PrintWriter ( new OutputStreamWriter (nextSocket.getOutputStream( ) ));

Cont. In this example, the code will block indefinitely while reading a response from a client If we want it to service multiple clients concurrently threads must be used (only for a complex application)

Creating a TCP Server A simple TCPEchoServer

Another Example DayTimeClient DayTimeServer

Summary TCP Clients and servers How to write and to run a simple TCP socket client using java.net.Socket How to write and to run a simple TCP socket server using java.net.ServerSocket