Network Read/Write

advertisement
Network Read/Write
Review of Streams and Files
• java.io package
• InputStream and OutputStream classes for binary bytes
• Reader and Writer classes for characters
• Reading files: FileReader class
– FileReader reads 1 char at a time; use BufferedReader
– readLine() returns null at end of file
Example 1
FileReader frdr = new FileReader(“filename.txt”);
BufferedReader rdr = new BufferedReader( frdr );
String line = rdr.readLine();
rdr.close();
Example 2
BufferedReader rdr = new BufferedReader(
new InputStreamReader( System.in ));
Review Output Streams
• FileWriter
– Create a FileWriter, write to it and close it.
– You must write line separator characters
FileWriter fw = new FileWriter(“filename.txt”);
fw.write(“abc def\n”);
fw.close();
• PrintWriter
– print() and println() will take of line separator characters.
PrintWriter pw = new PrintWriter( new
FileWriter(“filename.txt”));
pw.print( “abc “);
pw.println( “def”);
pw.close();
• Exceptions: IOException
– File methods must be in a try/catch block for IOException
Sockets
• Data stream between client and server
– Have to deal with security firewalls
• Client
– Create a Socket
• Arguments: host address or name, listener port number
– Create PrintWriter from the socket
– Create BufferedReader from the socket
– Close socket when done.
• Server
– Create ServerSocket (port number )
– Wait for incoming connection from client
– Accept connection
• A new port number is assigned to connection.
– Create BufferedReader, PrintWriter using Socket
• Reading and writing is typically done on separate thread so that the main thread
that is listening for incoming connections is not blocked.
– Close socket when done.
Get Official Time from Time Server
try {
// Step1. Create a Socket object instance
Socket s = new Socket("utcnist.colorado.edu", 13);
// Step 2. Create a BufferedReader instance
InputStream is = s.getInputStream();
InputStreamReader isrdr = new InputStreamReader(is);
BufferedReader rdr = new BufferedReader(isrdr);
// Step 3. Repeat readLine() method until null value
String line = rdr.readLine();
while (line!=null){
System.out.println(line);
line = rdr.readLine();
};
// Step 4. Close the socket connection.
s.close();
} catch (Exception e){
System.out.println(e.getMessage());
}
Get Current Weather
Socket s = new Socket("weather.yahooapis.com", 80);
OutputStream os = s.getOutputStream();
OutputStreamWriter out = new OutputStreamWriter(os);
out.write("GET /forecastrss?w=2453280 HTTP/1.1\r\n"+
"Host: weather.yahooapis.com\r\n"+
"\r\n");
out.flush();
InputStream is = s.getInputStream();
InputStreamReader isrdr = new InputStreamReader(is);
BufferedReader rdr = new BufferedReader(isrdr);
String line = rdr.readLine();
while (line!=null){
.. Do something ..
line = rdr.readLine();
}
s.close();
Download