|
Distributed Computing This website demonstrates using wikis as teaching and learning tool. The course instructor is also happy to share the teaching materials here with those who find it readable. |
Lecture /
Java Network Programming - Part 1A Distributed Computing Lecture by Steven Choy Lecture Overview: Sockets and Stream - Overview of using socket - Client-Side Networking - Java Client general operation - Server-Side Networking - Java Server general operations - Class InetAddress - Class Socket - Class ServerSocket Sockets and StreamOverview of using socket
Class InetAddress
InetAddress getLocalHost() throws UnknownHostException; InetAddress getByName(String host) throws UnknownHostException; InetAddress[] getAllByName(String host) throws UnknownHostException;
Client-Side NetworkingClass Socket
Socket(String host, int port) throws IOException; Socket(InetAddress address, int port) throws IOException; Socket(String host, int port, InetAddress localAddr, int localPort) throws IOException; Socket(InetAddress host, int port, InetAddress localAddr, int localPort) throws IOException; InputStream getInputStream() throws IOException; OutputStream getOutputStream() throws IOException; void close() throws IOException;
Java Client - general operation
Example Code 1 - Getting web pages with Socketimport java.net.*; import java.io.*; public class SimpleGrabPage { public static void main(String[] args) throws IOException { String host = "www.ouhk.edu.hk"; int port = 80; // default port for HTTP String page = "/index.html"; Socket socket = new Socket(host, port); PrintWriter pw = new PrintWriter(socket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); pw.print("GET " + page + " HTTP/1.0\r\n\n"); pw.flush(); // ensure the request is sent out String line; while ((line = in.readLine()) != null) System.out.println(line); pw.close(); in.close(); socket.close(); } } Case Study 1: Client getting web pages
URL(String url) throws MalformedURLException String getProtocol() String getHost() int getPort() String getPath() /* * Java Network Programming, Second Edition * Merlin Hughes, Michael Shoffner, Derek Hamner * Manning Publications Company; ISBN 188477749X * * http://nitric.com/jnp/ * * Copyright (c) 1997-1999 Merlin Hughes, * Michael Shoffner, Derek Hamner; * all rights reserved; see license.txt for details. */ import java.net.*; import java.io.*; public class GrabPage { public GrabPage (String textURL) throws IOException { dissect (textURL); } protected String host, file; protected int port; protected void dissect (String textURL) throws MalformedURLException { URL url = new URL (textURL); host = url.getHost (); port = url.getPort (); if (port == -1) port = 80; file = url.getFile (); } public void grab () throws IOException { connect (); try { fetch (); } finally { disconnect (); } } protected Writer writer; protected BufferedReader reader; protected void connect () throws IOException { Socket socket = new Socket (host, port); // 1. Create scoket OutputStream out = socket.getOutputStream (); // 2. Get streams writer = new OutputStreamWriter (out, "latin1"); InputStream in = socket.getInputStream (); Reader reader = new InputStreamReader (in, "latin1"); this.reader = new BufferedReader (reader); } protected void fetch () throws IOException { writer.write ("GET " + file + " HTTP/1.0\r\n\n"); // 3. Access streams writer.flush (); PrintWriter console = new PrintWriter (System.out); String input; while ((input = reader.readLine ()) != null) console.println (input); console.flush (); } protected void disconnect () throws IOException { reader.close (); // 4&5. Close connection } public static void main (String[] args) throws IOException { Reader kbd = new FileReader (FileDescriptor.in); BufferedReader bufferedKbd = new BufferedReader (kbd); while (true) { String textURL; System.out.print ("Enter a URL: "); System.out.flush (); if ((textURL = bufferedKbd.readLine ()) == null) break; try { GrabPage grabPage = new GrabPage (textURL); grabPage.grab (); } catch (IOException ex) { ex.printStackTrace (); continue; } System.out.println ("- OK -"); } System.out.println ("exit"); } } Case Study 2: Client sending email
public void sendMail(String toAddress, String fromAddress, String subject, String messageBody) throws IOException, ProtocolException, UnknownHostException { messageArea.setText(""); printMessage("** Sending Mail Now **"); printMessage("** From : " + fromAddress); printMessage("** To : " + toAddress); printMessage("** Subject : " + subject); printMessage("** Message : " + messageBody); printMessage("-----------------------------------------------"); String messageRecv; // KL: Use your own ISP's SMTP server instead!! // String host = new String("mail.netvigator.com"); String host = new String("smtp.myrealbox.com"); Socket socket = new Socket(host, 25); //DataInputStream in = new DataInputStream(socket.getInputStream()); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); PrintStream out = new PrintStream(socket.getOutputStream()); messageRecv = in.readLine(); printMessage(messageRecv); if (!messageRecv.startsWith("220")) throw new ProtocolException(messageRecv); while (messageRecv.indexOf('-') == 3) { messageRecv = in.readLine(); printMessage(messageRecv); if (!messageRecv.startsWith("220")) throw new ProtocolException(messageRecv); } //out.println( "HELO " + host ); out.flush(); //messageRecv = in.readLine(); printMessage(messageRecv); //if (!messageRecv.startsWith("250")) // throw new ProtocolException(messageRecv); out.println( "MAIL FROM: " + fromAddress ); out.flush(); messageRecv = in.readLine(); printMessage(messageRecv); if (!messageRecv.startsWith("250")) throw new ProtocolException(messageRecv); out.println( "RCPT TO: " + toAddress ); out.flush(); messageRecv = in.readLine(); printMessage(messageRecv); if (!messageRecv.startsWith("250")) throw new ProtocolException(messageRecv); out.println( "DATA" ); out.flush(); messageRecv = in.readLine(); printMessage(messageRecv); if (!messageRecv.startsWith("354")) throw new ProtocolException(messageRecv); out.println("From: " + fromAddress); out.println("To: " + toAddress); out.println( "Subject: " + subject + "\n" ); out.flush(); out.println("Comment: Unauthenticated sender"); out.println("X-Mailer: SimpleSendMail"); out.println(""); out.println( messageBody ); out.println("."); out.flush(); messageRecv = in.readLine(); printMessage(messageRecv); if (!messageRecv.startsWith("250")) throw new ProtocolException(messageRecv); out.println("QUIT"); out.flush(); in.close(); printMessage("** Your mail has been sent."); socket.close(); return; } public void printMessage(String str) { messageArea.append(str + "\n"); return; } Case Study 3: Client querying DNS
Server-Side NetworkingClass ServerSocket
ServerSocket(int port) throws IOException; ServerSocket(int port, int backlog) throws IOException; ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException; Socket accept() throws IOException; void close() throws IOException; InetAddress getInetAddress(); int getLocalPort(); Socket Server - general operations1. Open a ServerSocket with a port
2. Loop forever
Accept a connection to create a Socket
Start a thread to handle the client
The client handling thread obtains streams from the socket and read/write the streams
Example Code 1 - Multithreaded echo server/* * Java Network Programming, Second Edition * Merlin Hughes, Michael Shoffner, Derek Hamner * Manning Publications Company; ISBN 188477749X * * http://nitric.com/jnp/ * * Copyright (c) 1997-1999 Merlin Hughes, * Michael Shoffner, Derek Hamner; * all rights reserved; see license.txt for details. */ import java.io.*; import java.net.*; public class MTEchoServer extends Thread { protected Socket socket; MTEchoServer (Socket socket) { this.socket = socket; } public void run () { try { InputStream in = socket.getInputStream (); OutputStream out = socket.getOutputStream (); out.write ("Welcome to the multithreaded echo server.\r\n".getBytes ("latin1")); byte[] buffer = new byte[1024]; int read; while ((read = in.read (buffer)) >= 0) out.write (buffer, 0, read); } catch (IOException ex) { ex.printStackTrace (); } finally { try { socket.close (); } catch (IOException ignored) { } } } public static void main (String[] args) throws IOException { if (args.length != 1) throw new IllegalArgumentException("Syntax: MTEchoServer <port>"); System.out.println ("Starting on port " + args[0]); // 1. Open ServerSocket ServerSocket server = new ServerSocket (Integer.parseInt (args[0])); while (true) { // 2. Accept connection & create thread Socket client = server.accept (); MTEchoServer echo = new MTEchoServer (client); echo.start (); } } } CourseworkYou need to do this coursework after this lecture. You will complete a TCP client program (called POPClient) to experience how to communicate with a POP server, how to obtain information about emails, and how to instruct the POP server to delete certain emails.
You need to demonstrate your work to your instructor in a tutorial session. Your instructor may ask you some questions to test your knowledge.
Extra materials for probing furtherThe Java Tutorial's specialized trails and lessons on custom networking. A good introduction to the Java platform's powerful networking features.
Peter van der Linden covers the fundamentals of Java networking—such as using a socket to communicate with another computer, writing a Java program to send email, and creating a server socket to listen for incoming requests.
This is the website of a book about Java network programming. It contains some program examples for your possible interests.
This tutorial is aimed for programmers with at least a little experience with Java.
It provides a number of sample Java classes that Neal has written. It also contains links to other places containing Java sample codes.
Thanks for ReadingIf you would rather like to have this lecture note in printed format, please click the print action link in the top right corner. If you find any problem in this lecture note, please feel free to reach Steven by steven@findaway.hk |