Java Reference
In-Depth Information
public
public class
class
EchoServerThreaded
EchoServerThreaded
{
public
public static
static final
final
int
int
ECHOPORT
=
7
;
public
public static
static
void
void
main
(
String
[]
av
)
{
new
new
EchoServerThreaded
().
runServer
();
}
public
public
void
void
runServer
()
{
ServerSocket sock
;
Socket clientSocket
;
try
try
{
sock
=
new
new
ServerSocket
(
ECHOPORT
);
System
.
out
.
println
(
"EchoServerThreaded ready for connections."
);
/* Wait for a connection */
while
while
(
true
true
){
clientSocket
=
sock
.
accept
();
/* Create a thread to do the communication, and start it */
new
new
Handler
(
clientSocket
).
start
();
}
}
catch
catch
(
IOException e
) {
/* Crash the server if IO fails. Something bad has happened */
System
.
err
.
println
(
"Could not accept "
+
e
);
System
.
exit
(
1
);
}
}
/** A Thread subclass to handle one client conversation. */
class
class
Handler
extends
Thread
{
Socket sock
;
Handler
extends
Handler
(
Socket s
) {
sock
=
s
;
}
public
public
void
void
run
() {
System
.
out
.
println
(
"Socket starting: "
+
sock
);
try
try
{
BufferedReader is
=
new
new
BufferedReader
(
new
new
InputStreamReader
(
sock
.
getInputStream
()));