Java Reference
In-Depth Information
}
}
Returning Object Information Across a Network Connection
Problem
You need to return an object across a network connection.
Solution
Create the object you need, and write it using an
ObjectOutputStream
created on top of the
socket's output stream.
Discussion
cess), is a program that constructs a
Date
object each time it's connected to and returns it to
the client.
Example 16-5. DaytimeObjectServer.java
public
public class
DaytimeObjectServer
{
/** The TCP port for the object time service. */
public
class
DaytimeObjectServer
public static
static final
final
short
short
TIME_PORT
=
1951
;
public
public static
void
main
(
String
[]
argv
) {
ServerSocket sock
;
Socket clientSock
;
try
static
void
try
{
sock
=
new
new
ServerSocket
(
TIME_PORT
);
while
while
((
clientSock
=
sock
.
accept
()) !=
null
null
) {
System
.
out
.
println
(
"Accept from "
+
clientSock
.
getInetAddress
());
ObjectOutputStream os
=
new
new
ObjectOutputStream
(
clientSock
.
getOutputStream
());
// Construct and write the Object
os
.
writeObject
(
new
new
Date
());