Basic Sockets
- Networking is built into the Java language and part of the java.net package (think import).
- Java has the URL class for representing a resource on the
World Wide Web.
- Networking support in Java includes sockets, which is used for coding
client/server communication.
- A very useful class for using sockets is the Sockets class.
- Once a Socket connection is established, communication is done through streams with standard I/O.
- For getting information from the server, you can use socketObj.getInputStream() to
create a BufferedReader, then call the readLine() method.
- For sending information to the server, use socketObj.getOutputStream() to create a PrintWriter, then call the println() method.
- Another mechanism for sockets communication is to use datagrams and not maintain the connection (like a Socket does).
- You can create a simple client Socket with:
Socket s = new Socket("hostname", portNumber);
- Once you have the Socket, get an input stream for reading data with code like this:
InputStream in = s.getInputStream();
- Once you have the Socket, get an output stream for writing with code like this:
OutputStream out = s.getOutputStream();
- The server Socket is created with the ServerSocket class.
- Look at the java.net package in the Java API Doc for more classes.