BASIC CONCEPTS
Socket Basics
A socket is a connection between two hosts. It can perform seven basic operations:
Java programs normally use client sockets in the following fashion:
Socket Class
Constructors
public Socket(String host, int port) throws UnknownHostException, IOException
Example:
Socket toOReilly = new Socket ("www.oreilly.com", 80);
public Socket(InetAddress host, int port) throws IOException
InetAddress OReilly = InetAddress.getByName("www.oreilly.com");
Socket OReillySocket = new Socket(OReilly, 80);
public Socket(String host, int port, InetAddress interface, int localPort) throws IOException
EXAMPLE
InetAddress fddi = InetAddress.getByName("fddisunsite.oit.unc.edu");
Socket OReillySocket = new Socket("www.oreilly.com", 80, fddi, 0);
public Socket(InetAddress host, int port, InetAddress interface, int localPort) throws IOException
EXAMPLE:
InetAddress metalab = InetAddress.getByName("metalab.unc.edu");
InetAddress oreilly = InetAddress.getByName("www.oreilly.com");
Socket oreillySocket = new Socket(oreilly, 80, metalab, 0);
Getting Information About a Socket
Methods
public InetAddress getInetAddress( )
Socket theSocket = new Socket("java.sun.com", 80);
InetAddress host = theSocket.getInetAddress( );
System.out.println("Connected to remote host " + host);
public int getPort( )
Socket theSocket = new Socket("java.sun.com", 80);
int port = theSocket.getPort( );
System.out.println("Connected on remote port " + port);
public int getLocalPort( )
Socket theSocket = new Socket("java.sun.com", 80, true);
int localPort = theSocket.getLocalPort( );
System.out.println("Connecting from local port " + localPort);
public InetAddress getLocalAddress( )
Socket theSocket = new Socket(hostname, 80);
InetAddress localAddress = theSocket.getLocalAddress( );
System.out.println("Connecting from local address " + localAddress);
Get a Socket's Information
import java.net.*; import java.io.*;
public class SocketInfo {
public static void main(String[] args) { for (int i = 0; i < args.length; i++) { try {
Socket theSocket = new Socket(args[i], 80); System.out.println("Connected to " + theSocket.getInetAddress( ) + " on port " + theSocket.getPort( ) + " from port "
+ theSocket.getLocalPort( ) + " of " + theSocket.getLocalAddress( )); } // end try
catch (UnknownHostException e)
{
System.err.println("I can't find " + args[i]);
}
catch (SocketException e) { System.err.println("Could not connect to " + args[i]);
}
catch (IOException e) { System.err.println(e);
}
} // end for
} // end main
} // end SocketInfo
Output
% java SocketInfo www.oreilly.com www.oreilly.com www.macfaq.com
shock.njit.edu
Connected to www.oreilly.com/198.112.208.23 on port 80 from port
46770 of calzone. oit.unc.edu/152.2.22.81
Connected to www.oreilly.com/198.112.208.23 on port 80 from port
46772 of calzone.
oit.unc.edu/152.2.22.81
Connected to www.macfaq.com/204.162.81.201 on port 80 from port 46773 of calzone.
oit.unc.edu/152.2.22.81
Could not connect to shock.njit.edu
public InputStream getInputStream( ) throws IOException
functionality—DataInputStream or InputStreamReader, for example—before reading
public void close( ) throws IOException
Sockets for Servers
The basic life cycle of a server is:
Constructors
There are three public ServerSocket constructors:
public ServerSocket(int port) throws IOException, BindException ServerSocket httpd = new ServerSocket(80);
public ServerSocket(int port, int queueLength) throws IOException, BindException ServerSocket httpd = new ServerSocket(5776, 100);
public ServerSocket(int port, int queueLength, InetAddress bindAddress) throws IOException
ServerSocket httpd = new ServerSocket(5776, 10, InetAddress.getHostByName("metalab.unc.edu")); Accepting and Closing Connections
public Socket accept( ) throws IOException ServerSocket server = new ServerSocket(5776); while (true)
{
Socket connection = server.accept( );
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream( )); out.write("You've connected to this server. Bye-bye now.\r\n");
Sockets for Servers
The basic life cycle of a server is:
Constructors
There are three public ServerSocket constructors:
public ServerSocket(int port) throws IOException, BindException ServerSocket httpd = new ServerSocket(80);
public ServerSocket(int port, int queueLength) throws IOException, BindException ServerSocket httpd = new ServerSocket(5776, 100);
public ServerSocket(int port, int queueLength, InetAddress bindAddress throws IOException
ServerSocket httpd = new ServerSocket(5776, 10, InetAddress.getHostByName("metalab.unc.edu")); Accepting and Closing Connections
public Socket accept( ) throws IOException ServerSocket server = new ServerSocket(5776); while (true)
{
Socket connection = server.accept( ); OutputStreamWriter out
= new OutputStreamWriter(connection.getOutputStream( )); out.write("You've connected to this server. Bye-bye now.\r\n");
connection.close( );
}
Socket Options
public void setSoTimeout(int timeout) throws SocketException
ServerSocket server = new ServerSocket(2048); server.setSoTimeout(30000); // block for no more than 30 seconds try {
Socket s = server.accept( );
// handle the connection // ...
Chat operation :
ChatClient.java
/* ChatClient.java */
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
class ChatClient {
private static int port = 1001; /* port to connect to */
private static String host = "localhost"; /* host to connect to */
public static void main (String[] args) throws IOException {
Socket server;
PrintWriter out = null;
try {
/* try to open a socket to the server at the given host:port */
server = new Socket(host, port);
/* obtain an output stream to the server
*/
out = new PrintWriter(server.getOutputStream(), true);
} catch (UnknownHostException e) { System.err.println(e); System.exit(1);
}
BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in));
String msg;
/* loop reading lines from stdin and output what was read
* to the server */
while ((msg = stdIn.readLine()) != null) { out.println(msg);
}
}
}
ChatServer.java
/* ChatServer.java */
import java.net.ServerSocket; import java.net.Socket;
import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader;
class ChatServer {
private static int port = 1001; /* port the server listens on */
public static void main (String[] args) throws IOException {
ServerSocket server = null;
try {
server = new ServerSocket(port); /* start listening on the port */
} catch (IOException e) { System.err.println("Could not listen on
port: " + port); System.err.println(e); System.exit(1);
}
Socket client = null; try {
client = server.accept(); } catch (IOException e) {
System.err.println("Accept failed."); System.err.println(e); System.exit(1);
}
/* obtain an input stream to the client */ BufferedReader in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
String msg;
/* loop reading lines from the client and display them */
while ((msg = in.readLine()) != null) { System.out.println("Client says: " +msg);
}
}
}
Setting Socket Options
public void setTcpNoDelay(boolean on) throws SocketException public boolean getTcpNoDelay( ) throws SocketException
SO_LINGER
public void setSoLinger(boolean on, int seconds) throws SocketException
public int getSoLinger( ) throws SocketException
SO_TIMEOUT
public void setSoTimeout(int milliseconds)throws SocketException public int getSoTimeout( ) throws SocketException
Usually when a read() method tries to read data from a socket the program will block until the data arrives. However, if you set the SO_TIMEOUT property, the read() will only wait the specified number of milliseconds. Then, if no data was received, it will throw an InterruptedIOException. In this case the Socket will not break the connection so you can reuse the socket. The timeout period is expressed in millisecond as an argument to setSoTimeout(): 0 is the default and means "no timeout".
It is a often a good idea to set the timeout to a non-zero value to prevent deadlock of your program in case of remote crash.
SO_RCVBUF
This method returns the no. of bytes in the buffer that can be used for input from this socket
public void setReceiveBufferSize(int size) // Java 1.2 throws SocketException, IllegalArgumentException
public int getReceiveBufferSize( ) throws SocketException
SO_SNDBUF
There are methods to get and set the suggested send buffer size used for network output:
public void setSendBufferSize(int size) // Java 1.2 throws SocketException, IllegalArgumentException
public int getSendBufferSize( ) throws SocketException
SO_KEEPALIVE
SO_KEEPALIVE on and off and to determine its current state:
public void setKeepAlive(boolean on) throws SocketException // Java1.3 public boolean getKeepAlive( ) throws SocketException // Java 1.3
The SO_KEEPALIVE option causes a packet (called a 'keepalive probe') to be sent to the remote system if a long time (by default, more than 2 hours) passes with no other data being sent or received. This packet is designed to provoke an ACK response from the peer. This enables detection of a peer which has become unreachable (e.g. powered off or disconnected from the net).
TCPEchoServer.java
public class EchoServer {
public static final int PORT = 10101;
public static void main (String[] args) throws IOException { ServerSocket s = new ServerSocket(PORT); System.out.println("Started: " + s);
try {
Socket socket = s.accept(); try {
System.out.println("Connection accepted: "+ socket); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(new BufferedWriter (
new OutputStreamWriter(socket.getOutputStream())),true); while (true) {
String str = in.readLine();
if (str.equals("END")) break; System.out.println("Echoing: " + str); out.println(str);
}
} finally { socket.close();
}} finally { s.close();
} } }
TCPEchoClient.java
import java.net.*; import java.io.*;
public class EchoClient {
public static void main(String[] args) { String hostname = "localhost";
if (args.length > 0) { hostname = args[0];
}
PrintWriter out = null; BufferedReader networkIn = null; try {
Socket theSocket = new Socket(hostname, 7); networkIn = new BufferedReader(
new InputStreamReader(theSocket.getInputStream())); BufferedReader userIn = new BufferedReader(new InputStreamReader (System.in));
out = new PrintWriter(theSocket.getOutputStream( )); System.out.println("Connected to echo server"); while (true) {
String theLine = userIn.readLine( ); if (theLine.equals(".")) break; out.println(theLine);
out.flush( ); System.out.println(networkIn.readLine( ));
}} // end try
catch (IOException e) { System.err.println(e);
}
finally { try {
if (networkIn != null) networkIn.close( ); if (out != null) out.close( );
}catch (IOException e) {} }} // end main
} // end EchoClient
Source: http://www.snscourseware.org/snsct/files/CW_588c6c9f9d686/Sockets.docx
Web site to visit: http://www.snscourseware.org
Author of the text: indicated on the source document of the above text
If you are the author of the text above and you not agree to share your knowledge for teaching, research, scholarship (for fair use as indicated in the United States copyrigh low) please send us an e-mail and we will remove your text quickly. Fair use is a limitation and exception to the exclusive right granted by copyright law to the author of a creative work. In United States copyright law, fair use is a doctrine that permits limited use of copyrighted material without acquiring permission from the rights holders. Examples of fair use include commentary, search engines, criticism, news reporting, research, teaching, library archiving and scholarship. It provides for the legal, unlicensed citation or incorporation of copyrighted material in another author's work under a four-factor balancing test. (source: http://en.wikipedia.org/wiki/Fair_use)
The information of medicine and health contained in the site are of a general nature and purpose which is purely informative and for this reason may not replace in any case, the council of a doctor or a qualified entity legally to the profession.
The texts are the property of their respective authors and we thank them for giving us the opportunity to share for free to students, teachers and users of the Web their texts will used only for illustrative educational and scientific purposes only.
All the information in our site are given for nonprofit educational purposes