Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Socket Programming Using JAVA Asma Shakil Semester 1, 2008/2009."— Presentation transcript:

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

2 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.

3 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.

4 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

5 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

6 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

7 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

8 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.

9 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

10 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

11 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 1023. can only be used by system (or root) processes or by programs executed by privileged users. The Registered Ports are those from 1024 through 49151. can be used by ordinary user processes or programs executed by ordinary users. The Dynamic and/or Private Ports are those from 49152 through 65535.

12 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

13 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

14 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

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

16 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

17 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); }

18 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

19 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); }

20 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);

21 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);

22 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

23 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); }

24 Creating a TCP Client A simple TCPEchoClient

25 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

26 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

27 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

28 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

29 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

30 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

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

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

33 Creating a TCP Server A simple TCPEchoServer

34 Another Example DayTimeClient DayTimeServer

35 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


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

Similar presentations


Ads by Google