Java Reference
In-Depth Information
servSock
=
new
new
ServerSocket
(
ChatProtocol
.
PORTNUM
);
System
.
out
.
println
(
"DarwinSys Chat Server Listening on port "
+
ChatProtocol
.
PORTNUM
);
}
public
public
void
void
runServer
() {
try
try
{
while
while
(
true
true
) {
Socket userSocket
=
servSock
.
accept
();
String hostName
=
userSocket
.
getInetAddress
().
getHostName
();
System
.
out
.
println
(
"Accepted from "
+
hostName
);
ChatHandler cl
=
new
new
ChatHandler
(
userSocket
,
hostName
);
String welcomeMessage
;
synchronized
synchronized
(
clients
) {
clients
.
add
(
cl
);
iif
(
clients
.
size
() ==
1
) {
welcomeMessage
=
"Welcome! you're the first one here"
;
}
else
else
{
welcomeMessage
=
"Welcome! you're the latest of "
+
clients
.
size
() +
" users."
;
}
}
cl
.
start
();
cl
.
send
(
CHATMASTER_ID
,
welcomeMessage
);
}
}
catch
catch
(
IOException e
) {
log
(
"IO Exception in runServer: "
+
e
);
}
}
protected
protected
void
void
log
(
String s
) {
System
.
out
.
println
(
s
);
}
/**
* The remainder of this file is an inner class that is
* instantiated once to handle each conversation.
*/
protected
protected class
extends
Thread
{
/** The client socket */
protected
class
ChatHandler
ChatHandler
extends
protected
Socket clientSock
;
/** BufferedReader for reading from socket */
protected
protected
BufferedReader is
;
/** PrintWriter for sending lines on socket */
protected
protected
PrintWriter pw
;