View
212
Download
0
Category
Preview:
Citation preview
Sockets For Clients
Instructors: Fu-Chiung Cheng
(鄭福炯 )Associate Professor
Computer Science & EngineeringTatung University
Contents
• The Socket class
• Telnet and Telnet protocols
• Socket information
• Socket Options
• InetAddress class
Socket
• A socket is a connection between two hosts• Socket: client and server socket
– Socket class (client) and ServerSocket (server)
• Client socket operations:– connect to a remote machine (a.k.a. server)– send data– receive data– close a connection
Server Socket
• Server Socket operations:– connect to a remote machine (a.k.a. server)– send data– receive data– close a connection– bind to a port (register the port to host) – listen for incoming data– accept connections from remote machines on the bound part
Telnet and Telnet Protocols
• Telnet command
– %telnet localhost 25 or telnet 140.129.20.87 25
• Port 25 provides SMTP (Simple Mail Transfer Protocol) service.
• Protocol: Set of rules and conventions used by communicating participants
• check page 303 for the SMTP protocol – Type: HELO command
– Reponse: 250 gamma. Hello alpha.cse.ttu.edu.tw [140.129.20.247], pleased to meet you
Telnet and Telnet Protocols
– Type HELP …
214-Commands:214- HELO MAIL RCPT DATA RSET214- NOOP QUIT HELP VRFY EXPN214-For more info use "HELP <topic>".214-smtp214-To report bugs in the implementation contact Sun
Microsystems214-Technical Support.214-For local information contact postmaster at this site.214 End of HELP info
Socket Class
• Client-side TCP operations• URL, URLConnection, Applet and JEditorPane use Socket for client
communication.• Constructors: (page 307-310)
– Socket public Socket(InetAddress address,int port)– public Socket(String host, int port, InetAddress localAddr, int localPort)– public Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
Socket Class
• Socket theSocket = new Socket("140.129.20.87", 13);– Connect to host "140.129.20.87“ and – use port 13 service
• InetAddress fddi = new InetAddress(“fddisunsie.oit.unc.edu”); Socket theSocket = new Socket(www.oreilly.com, 80, fddi, 0)
– Use fddi network interface– Local port 1024~65535
Socket Information
• public InetAddress getInetAddress()– Returns the address to which the socket is
connected. – Returns: the remote IP address to which this
socket is connected.
• public InetAddress getLocalAddress() – Gets the local address to which the socket is
bound.– Returns:the local address to which the socket is
bound.
Socket Information
• public int getPort() – Returns the remote port to which this socket is
connected.– Returns:the remote port number to which this
socket is connected
• public int getLocalPort() – Returns the local port to which this socket is
bound.– Returns:the local port number to which this socket
is connected.
Socket Information
• Example 10-3 (SocketInfo) on page 313• Check www.ttu.edu.tw and 140.129.20.83• Outputs:
– Connected to 140.129.20.83/140.129.20.83 on port 80 from port 1118 of JAVA.ttu.edu.tw/140.129.20.89
– Connected to www.ttu.edu.tw/140.129.21.6 on port 80 from port 1122 of JAVA.ttu.edu.tw/140.129.20.89
Socket Information
• public InputStream getInputStream()– Get the input stream for this socket.– Returns:an input stream for reading bytes
from this socket.
• public OutputStream getOutputStream()– Get the output stream for this socket.– Returns:an output stream for writing bytes
to this socket.
Socket Information
• Example 10-4 (Daytime Protocol Client) on page 314
• Daytime protocol: Connect to 140.129.20.87 and port 13
• Use getInputStream to read the daytime • Outputs:
– It is Tue Mar 27 09:45:43 2001 at 140.129.20.87
Socket Information
• Example 10-4 (Daytime Protocol Client) on page 314
• Daytime protocol: Connect to 140.129.20.87 and port 13
• Use getInputStream to read the daytime • Outputs:
– It is Tue Mar 27 09:45:43 2001 at 140.129.20.87
• More complicate sample: Time protocol on page 317
Socket Information
• Example 10-6 (Echo Protocol Client) on page 321
• Echo protocol: Connect to 140.129.20.87 and port 7
• You may try telnet 140.129.20.87 7• Use getInputStream to read the echo string
from server • Use getOutputStream to write string to server
Closing the Socket
• It is very good practice to close sockets.• System may hit max number of sockets before GC
kicks in. (Especially for Browser app.)• public void close()
– Closes this socket.
• public void shutdownInput() – Places the input stream for this socket at "end of stream". – Any data sent to the input stream side of the socket is
acknowledged and then silently discarded. – If you read from a socket input stream after invoking
shutdownInput() on the socket, the stream will return EOF.
Closing the Socket
• public void shutdownOutput()– Disables the output stream for this socket. – For a TCP socket, any previously written
data will be sent followed by TCP's normal connection termination sequence.
– If you write to a socket output stream after invoking shutdownOutput() on the socket, the stream will throw an IOException.
Closing the Socket
• Example: PortScan on page 323• Code sample: close a socket
finally {
try {
if (connection != null) connection.close();
}
catch (IOException e) {}
}
Socket Options
• public void setTcpNoDelay(boolean on)– Enable/disable TCP_NODELAY
(disable/enable Nagle's algorithm).– Parameters:on - true to enable
TCP_NODELAY, false to disable
• public boolean getTcpNoDelay()– Tests if TCP_NODELAY is enabled.– Returns:a boolean indicating whether or
not TCP_NODELAY is enabled.
Socket Options
• Datagrams not yet been sent but Socket is closed• public void setSoLinger(boolean on, int linger)
– Enable/disable SO_LINGER with the specified linger time in seconds.
– The maximum timeout value is platform specific. – The setting only affects socket close.
• public int getSoLinger()– Returns setting for SO_LINGER. – -1 returns implies that the option is disabled.
• Example:– If (s.getSoLinger() == -1) s.setSoLinger(true, 240);
Socket Options
• public void setSoTimeout(int timeout)– Enable/disable SO_TIMEOUT with the specified
timeout, in milliseconds. – With this option set to a non-zero timeout, a read() call
on the InputStream associated with this Socket will block for only this amount of time.
– If the timeout expires, a java.io.InterruptedIOException is raised, though the Socket is still valid.
– The option must be enabled prior to entering the blocking operation to have effect.
– The timeout must be > 0. – A timeout of zero is interpreted as an infinite timeout.
Socket Options
• public int getSoTimeout()– Returns setting for SO_TIMEOUT. – 0 returns implies that the option is disabled
(i.e., timeout of infinity).
• Example:– If (s.getSoTimeout() == 0) s.setSoTimeout(180000);
Socket Options
• public void setSendBufferSize(int size)– Sets the SO_SNDBUF option to the specified value for
this Socket. – The SO_SNDBUF option is used by the platform's
networking code as a hint for the size to set the underlying network I/O buffers.
– Increasing buffer size can increase the performance of network I/O for high-volume connection, while decreasing it can help reduce the backlog of incoming data.
– Because SO_SNDBUF is a hint, applications that want to verify what size the buffers were set to should call getSendBufferSize()
Socket Options
• public int getSendBufferSize()– Get value of the SO_SNDBUF option for this
Socket, that is the buffer size used by the platform for output on this Socket
Socket Options
• public void setReceiveBufferSize(int size)– Sets the SO_RCVBUF option to the specified value for
this Socket. – The SO_RCVBUF option is used by the platform's
networking code as a hint for the size to set the underlying network I/O buffers.
– Increasing buffer size can increase the performance of network I/O for high-volume connection, while decreasing it can help reduce the backlog of incoming data.
– Because SO_RCVBUF is a hint, applications that want to verify what size the buffers were set to should call getReceiveBufferSize()
Socket Options
• public int getReceiveBufferSize()– Gets the value of the SO_RCVBUF option for
this Socket, that is the buffer size used by the platform for input on this Socket
Socket Options
• If SO_KEEPALIVE is turned on, then the client will occasionally send a data packet over an idle connection (once every two hours) just to make sure the server hasn’t crashed.
• public void setKeepAlive(boolean on)– Enable/disable SO_KEEPALIVE.– Parameters:on - whether or not to have socket keep
alive turned on.
• public boolean getKeepAlive()– Tests if SO_KEEPALIVE is enabled.
InetAddress Class
• public static InetAddress getByName(String host)– Determines the IP address of a host, given the host's
name. – The host name can either be a machine name, such as
"java.sun.com", or a string representing its IP address, such as "206.26.48.100".
• public static InetAddress[] getAllByName(String host)– Determines all the IP addresses of a host, given the host's
name. • public static InetAddress getLocalHost()
– Returns the local host.
InetAddress Class
• public InetAddress(String host)– Create a InetAddress of a host, given the host's
name. • public public byte[] getAddress()
– Returns the raw IP address of this InetAddress object. – The result is in network byte order: the highest order byte
of the address is in getAddress()[0].
• public String getHostAddress()– Returns the IP address string "%d.%d.%d.%d".
InetAddress Class
• public String getHostName() – Gets the host name for this IP address.
• public boolean isMulticastAddress() – Utility routine to check if the InetAddress is an IP
multicast address. – IP multicast address is a Class D address i.e first
four bits of the address are 1110.
Recommended