Java Reference
In-Depth Information
/** The client's host */
protected
protected
String clientIP
;
/** String form of user's handle (name) */
protected
protected
String login
;
/* Construct a Chat Handler */
public
public
ChatHandler
(
Socket sock
,
String clnt
)
throws
throws
IOException
{
clientSock
=
sock
;
clientIP
=
clnt
;
is
=
new
new
BufferedReader
(
new
new
InputStreamReader
(
sock
.
getInputStream
()));
pw
=
new
new
PrintWriter
(
sock
.
getOutputStream
(),
true
true
);
}
/** Each ChatHandler is a Thread, so here's the run() method,
* which handles this conversation.
*/
public
public
void
void
run
() {
String line
;
try
try
{
/*
* We should stay in this loop as long as the Client remains
* connected, so when this loop ends, we disconnect the client.
*/
while
while
((
line
=
is
.
readLine
()) !=
null
null
) {
char
char
c
=
line
.
charAt
(
0
);
line
=
line
.
substring
(
1
);
switch
switch
(
c
) {
case
case
ChatProtocol
.
CMD_LOGIN
:
iif
(!
ChatProtocol
.
isValidLoginName
(
line
)) {
send
(
CHATMASTER_ID
,
"LOGIN "
+
line
+
" invalid"
);
log
(
"LOGIN INVALID from "
+
clientIP
);
continue
continue
;
}
login
=
line
;
broadcast
(
CHATMASTER_ID
,
login
+
" joins us, for a total of "
+
clients
.
size
() +
" users"
);
break
break
;
case
case
ChatProtocol
.
CMD_MESG
:
iif
(
login
==
null
null
) {
send
(
CHATMASTER_ID
,
"please login first"
);
continue
continue
;
}
int
int
where
=
line
.
indexOf
(
ChatProtocol
.
SEPARATOR
);
String recip
=
line
.
substring
(
0
,
where
);