Title: Networking
1Networking
2Overview
- Manipulating URLs
- Reading a file on a web server
- Simple Server
- Simple Client
- Stream Socket Connections
- Datagrams
- Multithreaded Server
- Security
3Protocols
- TCP -- Transmission Control Protocol
- connection-oriented
- error checking
- Java stream sockets
- UDP -- User Datagram Protocol
- connectionless
- no error checking
- Java datagram sockets
4URLReader.java
import java.net. import java.io. public
class URLReader public static void
main(String args) throws Exception
URL doIt new URL("http//komar.cs.stthomas.edu")
BufferedReader in new
BufferedReader(
new InputStreamReader(
doIt.openStream())) String
inputLine while ((inputLine
in.readLine()) ! null)
System.out.println(inputLine)
in.close()
5URLReader output
U\qm498gtjava URLReader lthtmlgt ltheadgtlttitlegtKomar'
s Kornerlt/titlegtlt/headgt ltframesgt
ltframeset cols19, border0gt
ltframe name"index", src"iii.htm",scrolling"off"
gt ltframeset rows18, border0gt
ltframe name"headit",
src"headit.htm"gt ltframe
name"main", src"default.htm"gt
lt/framesetgt lt/framesetgt lt/framesgt lt/htmlgt
6ReadServerFile
// This program uses a JEditorPane to display
the // contents of a file on a Web server. import
java.awt. import java.awt.event. import
java.net. import java.io. import
javax.swing. import javax.swing.event. public
class ReadServerFile extends JFrame private
JTextField enter private JEditorPane contents
7ReadServerFile
public ReadServerFile() super(
"Simple Web Browser" ) Container c
getContentPane() enter new JTextField(
"Enter file URL here" ) enter.addActionList
ener( new ActionListener()
public void actionPerformed( ActionEvent e )
getThePage(
e.getActionCommand() )
)
8ReadServerFile
c.add( enter, BorderLayout.NORTH )
contents new JEditorPane()
contents.setEditable( false )
contents.addHyperlinkListener( new
HyperlinkListener() public void
hyperlinkUpdate( HyperlinkEvent e )
if ( e.getEventType()
HyperlinkEvent.EventType.ACTIVATED )
getThePage( e.getURL().toString()
) )
c.add( new JScrollPane( contents ),
BorderLayout.CENTER ) setSize( 400, 300
) show()
9ReadServerFile
private void getThePage( String location )
setCursor( Cursor.getPredefinedCursor(
Cursor.WAIT_CURSOR ) )
try contents.setPage( location )
enter.setText( location )
catch ( IOException io )
JOptionPane.showMessageDialog( this,
"Error retrieving specified URL",
"Bad URL", JOptionPane.ERROR_MESSAGE
) setCursor( Cursor.getPredefinedC
ursor( Cursor.DEFAULT_CURSOR
) )
10ReadServerFile
public static void main( String args )
ReadServerFile app new ReadServerFile()
app.addWindowListener( new
WindowAdapter() public void
windowClosing( WindowEvent e )
System.exit( 0 )
)
11ReadServerFile
12Simple Socket Server
- Create ServerSocket object
- ServerSocket s new ServerSocket(port,
queuesize) - Listen for a connection
- Socket connection s.accept()
- Get OuputStream and InputStream
- ObjectInputStream in new ObjectInputStream(conne
ction.getInputStream()) - ObjectOutputStream out new ObjectOutputStream(co
nnection.getOutputStream()) - Process the interchange
- Close connections
13Simple Socket Client
- Create the Socket object
- Socket connection new Socket(serverAddress,
port) - Use Socket methods getInputStream and
getOutputStream to communicate - Process the interaction
- Close the connections
14Knock Knock Server
import java.net. import java.io. public
class KnockKnockServer public static void
main(String args) throws IOException
ServerSocket serverSocket null try
serverSocket new ServerSocket(4444)
catch (IOException e)
System.err.println("Could not listen on port
4444.") System.exit(1)
15Knock Knock Server
Socket clientSocket null try
clientSocket serverSocket.accept()
catch (IOException e)
System.err.println("Accept failed.")
System.exit(1) PrintWriter
out new PrintWriter(
clientSocket.getOutputStream(), true)
BufferedReader in new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()))
16Knock Knock Server
String inputLine, outputLine
KnockKnockProtocol kkp new KnockKnockProtocol()
outputLine kkp.processInput(null)
out.println(outputLine) while
((inputLine in.readLine()) ! null)
outputLine kkp.processInput(inputLine)
out.println(outputLine) if
(outputLine.equals("Bye."))
break
17Knock Knock Server
out.close() in.close()
clientSocket.close() serverSocket.close()
18Knock Knock Protocol
import java.net. import java.io. public
class KnockKnockProtocol private static
final int WAITING 0 private static final
int SENTKNOCKKNOCK 1 private static final
int SENTCLUE 2 private static final int
ANOTHER 3 private static final int
NUMJOKES 5 private int state WAITING
private int currentJoke 0
19Knock Knock Protocol
private String clues "Turnip", "Little
Old Lady", "Atch",
"Who", "Who" private String answers
"Turnip the heat, it's cold in here!",
"I didn't know you could
yodel!", "Bless
you!", "Is there
an owl in here?",
"Is there an echo in here?"
20Knock Knock Protocol
public String processInput(String theInput)
String theOutput null if
(state WAITING) theOutput
"Knock! Knock!" state
SENTKNOCKKNOCK else if (state
SENTKNOCKKNOCK) if
(theInput.equalsIgnoreCase("Who's there?"))
theOutput cluescurrentJoke
state SENTCLUE else
theOutput "You're supposed to
say \"Who's there?\"! "
"Try again. Knock! Knock!"
21Knock Knock Protocol
else if (state SENTCLUE)
if (theInput.equalsIgnoreCase(cluescurrentJoke
" who?")) theOutput
answerscurrentJoke " Want another? (y/n)"
state ANOTHER else
theOutput "You're supposed to
say \""
cluescurrentJoke
" who?\"" "! Try
again. Knock! Knock!" state
SENTKNOCKKNOCK
22Knock Knock Protocol
else if (state ANOTHER)
if (theInput.equalsIgnoreCase("y"))
theOutput "Knock! Knock!"
if (currentJoke (NUMJOKES - 1))
currentJoke 0 else
currentJoke state
SENTKNOCKKNOCK else
theOutput "Bye." state
WAITING return
theOutput
23Knock Knock Client
import java.io. import java.net. public
class KnockKnockClient public static void
main(String args) throws IOException
Socket kkSocket null PrintWriter out
null BufferedReader in null
24Knock Knock Client
try kkSocket new
Socket("140.209.114.23", 4444) out
new PrintWriter(kkSocket.getOutputStream(),
true) in new BufferedReader(new
InputStreamReader(
kkSocket.getInputStream())) catch
(UnknownHostException e)
System.err.println("Don't know about host .")
System.exit(1) catch
(IOException e) System.err.println("
Couldn't get I/O for the connection")
System.exit(1)
25Knock Knock Client
BufferedReader stdIn new
BufferedReader( new InputStreamReader(S
ystem.in),1) String fromServer
String fromUser while ((fromServer
in.readLine()) ! null)
System.out.println("Server " fromServer)
if (fromServer.equals("Bye."))
break fromUser
stdIn.readLine() if (fromUser !
null) System.out.println("Client
" fromUser)
out.println(fromUser)
26Knock Knock Client
out.close() in.close()
stdIn.close() kkSocket.close()
27Knock Knock interaction
U\qm498gtjava KnockKnockClient Server Knock!
Knock! Who's there? Client Who's there? Server
Turnip Turnip who? Client Turnip who? Server
Turnip the heat, it's cold in here! Want another?
(y/n) n Client n Server Bye.
28Threaded
import java.net. import java.io. public
class KKMultiServer public static void
main(String args) throws IOException
ServerSocket serverSocket null boolean
listening true try
serverSocket new ServerSocket(4444)
catch (IOException e)
System.err.println("Could not listen on port
4444.") System.exit(-1)
while (listening) new
KKMultiServerThread(serverSocket.accept()).start()
serverSocket.close()
29Threaded
import java.net. import java.io. public
class KKMultiServerThread extends Thread
private Socket socket null public
KKMultiServerThread(Socket socket)
super("KKMultiServerThread") this.socket
socket public void run()
try PrintWriter out new
PrintWriter(
socket.getOutputStream(), true)
BufferedReader in new BufferedReader(
new InputStreamReader(
socket.getInputStream()))
30Threaded
String inputLine, outputLine
KnockKnockProtocol kkp new
KnockKnockProtocol() outputLine
kkp.processInput(null)
out.println(outputLine) while
((inputLine in.readLine()) ! null)
outputLine kkp.processInput(inputLine)
out.println(outputLine)
if (outputLine.equals("Bye"))
break
out.close() in.close()
socket.close() catch (IOException e)
e.printStackTrace()
31Datagram Communication
import java.io. public class QuoteServer
public static void main(String args) throws
IOException new QuoteServerThread().star
t()
32Datagram Communication
import java.io. import java.net. import
java.util. public class QuoteServerThread
extends Thread protected DatagramSocket
socket null protected BufferedReader in
null protected boolean moreQuotes true
public QuoteServerThread() throws IOException
this("QuoteServerThread")
33Datagram Communication
public QuoteServerThread(String name) throws
IOException super(name) socket new
DatagramSocket(4445) try in new
BufferedReader(new FileReader("one-liners.txt"))
catch (FileNotFoundException e)
System.err.println( "Could not open
quote file. Serving time instead.")
34Datagram Communication
public void run() while (moreQuotes)
try byte buf new
byte256 // receive request
DatagramPacket packet new
DatagramPacket( buf,
buf.length) socket.receive(packet)
// figure out response
String dString null if (in
null) dString new
Date().toString() else
dString getNextQuote() buf
dString.getBytes()
35Datagram Communication
InetAddress address
packet.getAddress() int port
packet.getPort() packet new
DatagramPacket( buf,
buf.length, address, port)
socket.send(packet) catch (IOException
e) e.printStackTrace()
moreQuotes false
socket.close()
36Datagram Communication
protected String getNextQuote() String
returnValue null try if
((returnValue in.readLine()) null)
in.close() moreQuotes
false returnValue "No more
quotes. Goodbye." catch
(IOException e) returnValue
"IOException occurred in server."
return returnValue
37Datagram Communication
import java.io. import java.net. import
java.util. public class QuoteClient
public static void main(String args) throws
IOException String host
"komar.cs.stthomas.edu" // get a
datagram socket DatagramSocket socket
new DatagramSocket()
38Datagram Communication
// send request byte buf new
byte256 InetAddress address
InetAddress.getByName(host)
DatagramPacket packet new DatagramPacket(
buf, buf.length,
address, 4445) socket.send(packet)
// get response packet new
DatagramPacket(buf, buf.length)
socket.receive(packet) // display
response String received new
String(packet.getData(), 0)
System.out.println("Quote of the Moment "
received) socket.close()
39Datagram Communication
U\qm498gtjava QuoteClient komar.cs.stthomas.edu Qu
ote of the Moment Life is wonderful. Without it
we'd all be dead. U\qm498gtjava QuoteClient
komar.cs.stthomas.edu Quote of the Moment Daddy,
why doesn't this magnet pick up this floppy disk?
40Security Considerations
- Applets cannot access local files
- Applets can only access files on the server from
which it was loaded - Signed Applets
- Identify trusted applets
- Can provide additional privileges on the client
machine
41Summary
- Manipulating URLs
- Reading a file on a web server
- Simple Server
- Simple Client
- Stream Socket Connections
- Datagrams
- Multithreaded Server
- Security