Advanced Java Applications: Shon Vick CMSC 331
Advanced Java Applications: Shon Vick CMSC 331
Advanced Java
Applications
Shon Vick
CMSC 331
UMBC
Networking
2
UMBC
Sockets
3
UMBC
What Is a Socket?
4
UMBC
How do Sockets work?
6
UMBC How does Java support Sockets
import java.io.*;
import java.net.*;
Output
Host Port
try {
echoSocket = new Socket(“avatar ", 7777);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new
InputStreamReader(echoSocket.getInputStream()));
}
catch …
Input
9
UMBC
Need to Catch Exceptions
}
catch (UnknownHostException e) {
System.err.println("Don't know about host: avatar.");
System.exit(1);
}
catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: avatar.");
System.exit(1);
} 10
UMBC
Simple Socket Example
out.close( );
in.close( );
stdIn.close( );
echoSocket.close( );
12
UMBC
Basic Steps
• Open a socket.
• Open an input stream and output stream to
the socket.
• Read from and write to the stream
according to the server's protocol.
• Close the streams.
• Close the socket.
13
UMBC
Same Basic Steps
14
UMBC
Server
18
UMBC
The newprotocol Client
socket.close();
19
UMBC
The newprotocol Server
output.writeObject( protocol );
20
UMBC
Reading and Writing Objects
22
UMBC
The read counterpart
23
UMBC
The Needed Java Framework
25
UMBC Deserialization
& Object Reflection
26
UMBC
Reflection Allows
28
UMBC
Examining Classes
29
UMBC
Retrieving Class Objects
Foo
Bar b = new Bar();
Class c = b.getClass();
Class s = c.getSuperclass(); Bar
30
UMBC Other Ways of Retrieving
Class Objects
31
UMBC
Getting the Class Name
printName(b);
}
static void printName(Object o) {
Class c = o.getClass();
String s = c.getName();
System.out.println(s);
33
}}
UMBC
Selected References
34
UMBC
More References
35