Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Socket

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

1

Sockets
A socket is a communication end point:
Is equivalent to a computer's network (hardware)

interface.
Allows a network application to "plug into" the

network. (Not physically, but metaphorically.)


Is a network programming interface: It is used for interprocess communication over

the network.
F

Is used by a process to communicate with a remote system via a transport protocol. Needs an IP address and a port number.

Sockets

were first introduced in Berkeley

UNIX.

An extension of the UNIX abstraction of file I/O concepts.

Now

are commonly supported in almost all modern operating systems for inter-systems communications.

Sockets are popularly used in client/server computing.


Provides two major types of services: Connection-oriented
F

Implemented on TCP

Short for Transmission Control Protocol. An end-to-end connection is established before data exchange can happen.
n

Similar to our phone system.

Data bytes are delivered in sequence.


n

Delivery of data is guaranteed.

Connection is terminated when finished.

3 F

Two modes:

Iterative (synchronous) Concurrent (asynchronous)

Connectionless
F

Implemented on UDP

Short for User Datagram Protocol. No connection is required before data transfer.
n

Similar to our postal system.

Data bytes may be missing or delivered out-of-order.

Two modes:

Iterative (synchronous) Concurrent (asynchronous)

Java supports client/server computing using sockets.


Java supports both connection-oriented and

connectionless services.
Java uses Socket for clients and ServerSocket for

servers in a connection-oriented environment.


F

The Socket class provides a Java programming interface to the TCP protocol.

Java uses DatagramSocket/DatagramPacket for

connectionless services.
F

The DatagramSocket class provides a Java programming interface to the UDP protocol.

The life cycles of the client/server model in Java. The life cycle of a client [Haro 97: p. 150]
1

a) A client socket is created using Socket(). b) The socket connects to a remote host. b.1) Done by Java on your behalf. b.2) A full-duplex connection. c) Data exchange between local and remote hosts. c.1) In need of an input stream to read data from server. c.2) In need of an output stream to send data to server. c.3) Meanings of data depend on protocols. d) Connection terminates after transmission of data is complete. d.1) Requests for data may be single or multiple in a connection, depending on protocols.
1

Elliotte Harold, Java Network Programming, O'Reilly, 1997, p. 150.

The life cycle of a server [Haro 97: p. 185]

a) A server socket is created on a particular port using ServerSocket(). b) The socket listens for an incoming connection request from a client on the port using accept(). c) Data exchange after connection is made. c.1) The server and client interact according to an agreed upon protocol. c.2) Either or both of getInputStream() and getOutputStream(), depending on the type of server, is called to exchange data with the client. d) The server, the client, or both closes the connection upon completion of data exchange. e) The server returns to b), and waits for the next connection request.
F

In asynchronous mode, the server spawns a thread to interact with the client in step c.2).

The Socket class


The Socket class represents a network connection. A socket is created typically with a hostname,

or an IP address, and a port number.


F

A (protocol) port is an abstraction used by a transport protocol to distinguish applications on a given host.

Port numbers range from 0 to 65,353. Numbers smaller than 1024 are reserved.

You may optionally specify the underlying communication protocol type to be one of:

Connection-oriented (default)
n

Stream-based (TCP).

Connectionless
n n

Datagram-based (UDP). Being replaced by DatagramSocket.

Six constructors Socket() Creates an unconnected socket, with the system-default type of SocketImpl. Socket(InetAddress address, int port) Creates a

stream socket and connects it to the specified port number at the specified IP address.
Socket(InetAddress address, int port, InetAddress localAddr, int localPort) Creates a socket and

connects it to the specified remote address on the specified remote port.


Socket(SocketImpl impl) Creates an

unconnected Socket with a user-specified SocketImpl.


Socket(String host, int port) Creates a stream

socket and connects it to the specified port number on the named host.
Socket(String host, int port, InetAddress localAddr, int localPort) Creates a socket and connects it

to the specified remote host on the specified remote port.

Useful Socket methods:


F

InetAddress getInetAddress()

Get the Internet address to which this Socket is connected.

InputStream getInputStream()

Get an InputStream for reading bytes from this Socket.

InetAddress getLocalAddress()

Get the local Internet address this Socket is using.

int getLocalPort()

Get the local port this Socket is using.

OutputStream getOutputStream()

Get an OutputStream for writing bytes to this Socket.

int getPort()

Get the remote port to which this Socket is connected.

10 [

Example: network echo


1 /* netWEcho 2 To echo user input from a remote host via the network 3 4 */ Syntax: netWEcho [remoteHost]

5 import java.io.*; 6 import java.net.*; 7 class netWEcho { 8 public static void main (String[] args) { 9 String host = "localhost"; // default is local host 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 if (args.length > 0) { host = args[0]; } try { Socket socketIO = new Socket(host, 7); // 7 is echo server DataInputStream socketIn = new DataInputStream(socketIO.getInputStream()); DataOutputStream socketOut = new DataOutputStream(socketIO.getOutputStream()); int userIn, socketEcho; final int EOF = -1; // to define EOF, for program readibility while ((userIn = System.in.read()) != EOF) { socketOut.writeByte(userIn); // write to socket socketEcho = socketIn.readByte(); // read from socket System.out.write(socketEcho); // print socket in } // end while socketIO.close(); } // end try

11 29 System.err.println(uhe); 30 } 31 catch(IOException ioe) { 32 System.out.println(ioe); 33 } 34 } // end main 35 } // end netWEcho

Program output

java netWEcho fau.edu Hello World! Hello World! ^D java netWEcho cse.fau.edu java.net.UnknownHostException: cse.fau.edu java netWEcho www.cse.fau.edu java.net.ConnectException: Connection refused java netWEcho Hello World! Hello World! ^D

12 [

Example: to find TCP ports


1 /* viewPorts 2 To find ports that host TCP services 3 Syntax: viewPorts [remote hostname] 4 Well-kown ports are specified in /etc/services 5 */ 6 import java.io.*; 7 import java.net.*; 8 class viewPorts {

9 public static void main (String[] args) { 10 Socket socketIn; 11 String host = "localhost"; 12 13 14 15 16 17 18 19 20 21 22 23 24 if (args.length > 0) { host = args[0]; } for (int i = 0; i < 1024; i++) { try { socketIn = new Socket(host, i); // to open a socket System.out.println("Port " + i + " hosts TCP service"); socketIn.close(); // to close the open socket } catch(UnknownHostException uhe) { System.err.println(uhe); break; }

25 catch(IOException ioe) { 26 // System.out.println("Port " + i + " does not host TCP service"); 27 // output statement is commented out to avoid a lengthy output 28 } 29 } // end for 30 } // end main 31 } // end viewPorts

13 [

Program output

java viewPorts fau.edu Port 7 hosts TCP service Port 9 hosts TCP service Port 13 hosts TCP service Port 19 hosts TCP service Port 21 hosts TCP service Port 23 hosts TCP service Port 25 hosts TCP service Port 37 hosts TCP service Port 53 hosts TCP service Port 80 hosts TCP service Port 111 hosts TCP service Port 512 hosts TCP service Port 513 hosts TCP service Port 514 hosts TCP service Port 515 hosts TCP service Port 540 hosts TCP service Port 867 hosts TCP service java viewPorts reality.cse.fau.edu Port 21 hosts TCP service Port 22 hosts TCP service Port 23 hosts TCP service Port 25 hosts TCP service Port 53 hosts TCP service Port 79 hosts TCP service Port 110 hosts TCP service Port 111 hosts TCP service Port 113 hosts TCP service Port 513 hosts TCP service Port 514 hosts TCP service

14 [

Example: to access smtp via socket


1 /* smtp 2 To access smtp (simple mail transfer protocol) via socket 3 4 */ Syntax: smtp [hostname]

5 import java.io.*; 6 import java.net.*; 7 class smtp { 8 public static void main (String[] args) { 9 String host = "localhost"; // default is local host 10 String mesg = "mail from: someone@who.you.know" + "\n" + 11 "rcpt to: sam@cse.fau.edu\n" + 12 "data\n" + 13 "This is a test\n" + 14 ".\n" + 15 "quit\n"; 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 if (args.length > 0) { host = args[0]; } try { Socket socketIO = new Socket(host, 25); // 25 is smtp server DataInputStream socketIn = new DataInputStream(socketIO.getInputStream()); DataOutputStream socketOut = new DataOutputStream(socketIO.getOutputStream()); socketOut.writeBytes(mesg); // write to socket while (true) { System.out.write(socketIn.readByte()); } } // end try catch(UnknownHostException uhe) { System.err.println(uhe); }

15 33 catch(IOException ioe) { 34 //System.out.println(ioe); 35 } 36 finally { // always executes if any part of try executes 37 System.out.println(); 38 //socketIO.close(); //not defined here 39 } 40 } // end main 41 } // end smtp

Program output

java smtp reality.cse.fau.edu 220 reality.cse.fau.edu ESMTP mailer ready at Sat, 15 May 1999 17:32:17 -250 someone@who.you.know... Sender ok 250 sam@cse.fau.edu... Recipient ok 354 Enter mail, end with "." on a line by itself 250 RAA07256 Message accepted for delivery 503 Need MAIL before RCPT 503 Need MAIL command 500 Command unrecognized: "This is a test" 500 Command unrecognized: "." 221 reality.cse.fau.edu closing connection telnet reality.cse.fau.edu 25 Trying 131.91.80.40... Connected to reality.cse.fau.edu. Escape character is '^]'. 220 reality.cse.fau.edu ESMTP mailer ready at Sat, 15 May 1999 17:34:38 -040 mail from: someone@who.you.know 250 someone@who.you.know... Sender ok rcpt to: sam@cse.fau.edu 250 sam@cse.fau.edu... Recipient ok data 354 Enter mail, end with "." on a line by itself This is a test . 250 RAA07266 Message accepted for delivery quit 221 reality.cse.fau.edu closing connection Connection closed by foreign host.

16

The ServerSocket class


This class implements server sockets. A server socket waits for requests to come in over

the network. It performs some operation based on that request, and then possibly returns a result to the requester.
The actual work of the server socket is performed by an instance of the SocketImpl class. An application can change the socket factory that

creates the socket implementation to configure itself to create sockets appropriate to the local firewall.
Three constructors ServerSocket(int port) Creates a server socket

on a specified port. A port of 0 creates a socket on any free port.


ServerSocket(int port, int backlog) Creates a

server socket and binds it to the specified local port number. The maximum queue length for

17

incoming connection request is set to the backlog parameter.


ServerSocket(int port, int backlog, InetAddress

bindAddr) Create a server with the specified port, listen backlog, and local IP address to bind to.

Things to know about ServerSocket: The port must be between 0 and 65535,

inclusive. If 0 is chosen as the port number, the host OS will select a free port for you. A port chosen in this manner is called an anonymous port.
The maximum queue length for incoming

connection requests is set to 50 by default on any port. The parameter backlog should be 50. If a connection request arrives when the queue is full, the connection is refused.
The bindAddr argument (the local InetAddress

the server will bind to) may be used on a multihomed host for a ServerSocket that will only accept connect requests to one of its addresses. If bindAddr is null, it will default accepting connections on any/all local addresses.

18 [

Example: to find the first free port


1 /* findAPort 2 To find a free port (to bind to) 3 4 */ Syntax: findAPort

5 import java.io.*; 6 import java.net.*; 7 class findAPort { 8 public static void main (String[] args) { 9 10 11 12 for (int i = 1024; i < 65535; i++) { try { ServerSocket freePort = new ServerSocket(i); System.out.println("The first free port is: " + i);

13 freePort.close(); // always a good practice to close when finished 14 System.exit(i); // to exit the loop and program; i is arbitrary 15 } catch(IOException ioe) { 16 // control falls into this block if there is a server on port i 17 } 18 } // end for 19 } // end main 20 } // end findAPort

Program output

The first free port is: 1024

19 [

Example: a daytime server


1 /* dayTmSer 2 To implement a specialized server -- reporting date and time 3 Syntax: dayTmSer Key points: . Server and client each needs a different socket. . Server response can be sent to client using PrintStream that chains to the client socket's getOutputStream() (for output to client) . accept() is used by server to listen for a connection request from client. Server blocks until a request is received. . This is a iterative server, serving one request at a time. . getSoTimeout() is used to set socket timeout so the server will not get stuck in the infinite loop forever. However, in applications, a server may wait forever for a client to connect. In this case, this method is not needed, or the amout of time for timeout is specified as 0. */

4 5 6 7 8 9 10 11 12 13 14 15

16 import java.io.*; 17 import java.net.*; 18 import java.util.Date; 19 public class dayTmSer { 20 public final static int daytimePort = 1300; // well-known port is 13 21 public static void main (String[] args) { 22 23 24 25 26 27 28 29 30 ServerSocket serSocket; // for server socket Socket cliSocket; // for client socket PrintStream prt; try { serSocket = new ServerSocket(daytimePort); try { while (true) { // an infinite loop serSocket.setSoTimeout(60000); // times out in 1 min cliSocket = serSocket.accept(); // listen for client request

20 31 prt = new PrintStream(cliSocket.getOutputStream()); 32 prt.println(new Date()); // send date/time to client 33 cliSocket.close(); // only one request per connection 34 } 35 } catch(InterruptedIOException ie) { // the timeout expires 36 System.out.println(ie); 37 } catch(IOException ioe) { // catch error on accept() 38 System.out.println(ioe); 39 } finally { 40 serSocket.close(); // close the server socket on error 41 } 42 } catch(IOException ioe) { // catch error on ServerSocket() 43 System.out.println(ioe); 44 } // outer try 45 } // end main 46 } // end dayTmSer

Program output (response to a client request)

telnet reality.cse.fau.edu 1300 Trying 131.91.80.40... Connected to reality.cse.fau.edu. Escape character is '^]'. Sun May 16 22:26:20 EDT 1999 Connection closed by foreign host # waiting java.io.InterruptedIOException: Accept timed out

21 [

Example: File and directory properties


1 /* fileDir 2 To deal with file & directory properties 3 Syntax: fileDir [filename] Key points: . This program takes one input filename as a commandline argument. . If there is no argument, default is the current directory. . A File object is created out of the input filename. . If the file referred to by the filename does not exist, program exists. . If the file is a directory, list all entries under it. . If it is a file, test to see if it is readable and writeable. . If it is neither a directory nor a file, indicate it. */

4 5 6 7 8 9 10 11 12

13 import java.io.*; 14 public class fileDir { 15 public static void main(String[] args) { 16 17 18 19 20 21 22 23 24 25 26 27 String filename = "."; // default is current dir if (args.length > 0) filename = args[0]; File file = new File(filename); if (!file.exists()) { // if there is no such filename System.out.println(filename + " does not exist!"); return; // program terminates } if (file.isDirectory()) { // if input filename is a directory String[] entryNames = file.list(); for (int i = 0; i < entryNames.length; i++) // list all entries System.out.println(entryNames[i]);

22 28 } else if (file.isFile()) { // if it is a file 29 if (file.canRead()) 30 System.out.println(filename + " is readable."); 31 if (file.canWrite()) 32 System.out.println(filename + " is writeabl.e"); 33 } else 34 System.out.println(filename + " is neither a file nor a directory."); 35 } // end main 36 } // end fileDir

Program output

Java fileDir viewPorts.java smtp.java netWEcho.java findAPort.java dayTmSer.java execCmd.java fileDir.java fileDir.class java fileDir nosuchfile nosuchfile does not exist! Java fileDir fileDir.class fileDir.class is readable. fileDir.class is writeabl.e java fileDir /dev/tty /dev/tty is neither a file nor a directory.

23 [

Example: to execute host commands


1 /* execCmd 2 To execute an external command 3 Syntax: execCmd cmd Key points: . This program needs one external command as a commandline argument. If missing, program exits using the return statement. . Use getRuntime() to get a Runtime object for the current platform so this object can be used to perform some system functions of the host OS. getRuntime() is a static method, direct access is allowed. . Runtime.exec() creates a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it, including performing input/output from/to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process. */

4 5 6 7 8 9 10 11 12 13 14 15

16 import java.io.*; 17 import java.lang.*; 18 public class execCmd { 19 public static void main (String[] args) { 20 21 22 23 24 25 26 27 28 29 if (args.length < 1) { System.out.println("Syntax: java execCmd command"); return; // no value to be returned } Runtime runTm = Runtime.getRuntime(); Process proc = null; try { proc = runTm.exec(args); BufferedReader execRes = new BufferedReader(new InputStreamReader(proc.getInputStream()));

24 30 String lineIn = null; 31 while ((lineIn = execRes.readLine()) != null) { 32 System.out.println(lineIn); 33 } 34 proc.destroy(); // to terminate the external process 35 } catch (Exception e) { 36 System.out.println(e); 37 } 38 } // end main 39 } // end execCmd

Program output

java execCmd Syntax: java execCmd command java execCmd date Tue May 18 11:04:11 EDT 1999 java execCmd echo Hello World! Hello World! java execCmd who | wc -l 26

25

The DatagramSocket class


This class represents a socket for sending and

receiving datagram packets.


Datagram packets are used to implement a

connectionless packet delivery service.


A datagram socket is the sending or receiving

point for a packet delivery service.


Each datagram packet, or datagram for short, sent

or received on a datagram socket is individually addressed and routed.


Each datagram is routed from one machine to

another based solely on information contained within that packet.


Multiple datagrams sent from one machine to

another may be routed differently, and may arrive in any order.


Three constructors DatagramSocket() Constructs a datagram socket

and binds it to any available port on the local host machine.

26

DatagramSocket(int port) Constructs a datagram

socket and binds it to the specified port on the local host machine.
DatagramSocket(int port, InetAddress laddr)

Creates a datagram socket, bound to the specified local address.

27

The DatagramPacket class


This class represents a datagram packet. The DatagramPacket class assembles data bytes

into packets called datagrams for delivery.


It disassembles and extracts data contents from

datagrams received from a remote site.


Four constructors DatagramPacket(byte[] buf, int length) Constructs a DatagramPacket for receiving

packets of length length.


DatagramPacket(byte[] buf, int offset, int length) Constructs a DatagramPacket for receiving

packets of length length, specifying an offset into the buffer.


DatagramPacket(byte[] buf, int length, InetAddress address, int port) Constructs a datagram

packet for sending packets of length length to the specified port number on the specified host.

28

DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port) Constructs a

datagram packet for sending packets of length length with offset offset to the specified port number on the specified host.

29

The SocketImpl class


The abstract class SocketImpl is a common

superclass of all classes that actually implement sockets.


It is used to create both client and server

sockets.
A "plain" socket implements these methods

exactly as described, without attempting to go through a firewall or proxy.

30

Typical C implementation of a client/server environment using sockets [Stev 98]2.

UDP Server
socket()
well-known port

bind() recvfrom()

UDP Client
socket() sendto()
data (request) blocks until connection from client

process request

recvfrom() close()

data (reply)

sendto()

Socket functions for UDP client-server

W. Richard Stevens, UNIX Network Programming, vol. 1, 2nd ed., Prentice Hall, 1998.

31

TCP Server
socket()
well-known port

bind() listen() accept()

TCP Client
socket()
connection establishment

blocks until connection from client

connect() write()

TCP 3-way handshake

data (request)

read()
process request

read() close()

data (reply)

write()

EOF notification

read() close()

Socket functions for TCP client-server

You might also like