Socket
Socket
Socket
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
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
UNIX.
Now
are commonly supported in almost all modern operating systems for inter-systems communications.
Implemented on TCP
Short for Transmission Control Protocol. An end-to-end connection is established before data exchange can happen.
n
3 F
Two modes:
Connectionless
F
Implemented on UDP
Short for User Datagram Protocol. No connection is required before data transfer.
n
Two modes:
connectionless services.
Java uses Socket for clients and ServerSocket for
The Socket class provides a Java programming interface to the TCP protocol.
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
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).
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
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
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
InetAddress getInetAddress()
InputStream getInputStream()
InetAddress getLocalAddress()
int getLocalPort()
OutputStream getOutputStream()
int getPort()
10 [
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
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 [
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 [
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 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
server socket and binds it to the specified local port number. The maximum queue length for
17
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 [
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
19 [
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
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 [
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 [
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
26
socket and binds it to the specified port on the local host machine.
DatagramSocket(int port, InetAddress laddr)
27
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
sockets.
A "plain" socket implements these methods
30
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()
W. Richard Stevens, UNIX Network Programming, vol. 1, 2nd ed., Prentice Hall, 1998.
31
TCP Server
socket()
well-known port
TCP Client
socket()
connection establishment
connect() write()
data (request)
read()
process request
read() close()
data (reply)
write()
EOF notification
read() close()