0% found this document useful (0 votes)
284 views32 pages

Java Socket Programming Examples

This document provides an overview and examples of Java socket programming. It summarizes four network applications written from scratch in Java using sockets: 1) a simple date client/server for one-way communication, 2) a capitalization client/server for two-way communication using threads, 3) a two-player tic-tac-toe game client/server, and 4) a multi-user chat client/server. It then provides details on implementing a date client/server and capitalization client/server to illustrate basic socket programming concepts.

Uploaded by

Rupali Vaiti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
284 views32 pages

Java Socket Programming Examples

This document provides an overview and examples of Java socket programming. It summarizes four network applications written from scratch in Java using sockets: 1) a simple date client/server for one-way communication, 2) a capitalization client/server for two-way communication using threads, 3) a two-player tic-tac-toe game client/server, and 4) a multi-user chat client/server. It then provides details on implementing a date client/server and capitalization client/server to illustrate basic socket programming concepts.

Uploaded by

Rupali Vaiti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Socket

Programming
Examples
Although most programmers probably do network programming using a nice library
with high-level application protocol (such as HTTP) support built-in, it's still useful to
have an understanding of how to code at the socket level. Here are a few complete
examples you can compile and run.

Overview
We will look at four network applications, written completely from scratch in
Java. We will see that we can write these programs without any knowledge
of the technologies under the hood (which include operating system
resources, routing between networks, address lookup, physical
transmission media, etc.)
Each of these applications use the client-server paradigm, which is roughly
1. One program, called the server blocks waiting for a client to connect
to it
2. A client connects
3. The server and the client exchange information until they're done
4. The client and the server both close their connection
The only pieces of background information you need are:

Hosts have ports, numbered from 0-65535. Servers listen on a port.


Some port numbers are reserved so you can't use them when you
write your own server.
Multiple clients can be communicating with a server on a given port.
Each client connection is assigned a separate socket on that port.
Client applications get a port and a socket on the client machine
when they connect successfully with a server.
The four applications are
A trivial date server and client, illustrating simple one-way
communication. The server sends data to the client only.
A capitalize server and client, illustrating two-way communication.
Since the dialog between the client and server can comprise an
unbounded number of messages back and forth, the server
is threaded to service multiple clients efficiently.
A two-player tic tac toe game, illustrating a server that needs to keep
track of the state of a game, and inform each client of it, so they can
each update their own displays.
A multi-user chat application, in which a server must broadcast
messages to all of its clients.

A Date Server and Client


The server
[Link]
[Link];
[Link];
[Link];

[Link];
[Link];
[Link];
/**
*[Link]
connects,it
*sendstheclientthecurrentdateandtime,thenclosesthe
*[Link]
simplest
*serveryoucanwrite.
*/
publicclassDateServer{
/**
*Runstheserver.
*/
publicstaticvoidmain(String[]args)throwsIOException
{
ServerSocketlistener=newServerSocket(9090);
try{
while(true){
Socketsocket=[Link]();
try{
PrintWriterout=
new
PrintWriter([Link](),true);
[Link](newDate().toString());
}finally{
[Link]();
}
}
}
finally{
[Link]();
}
}
}

The client

[Link]
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
/**
*Trivialclientforthedateserver.
*/
publicclassDateClient{
/**
*[Link]
dialog
*boxaskingfortheIPaddressorhostnameofahost
running
*thedateserver,thenconnectstoitanddisplaysthe
datethat
*itserves.
*/
publicstaticvoidmain(String[]args)throwsIOException
{
StringserverAddress=[Link](
"EnterIPAddressofamachinethatis\n"+
"runningthedateserviceonport9090:");
Sockets=newSocket(serverAddress,9090);
BufferedReaderinput=
newBufferedReader(new
InputStreamReader([Link]()));
Stringanswer=[Link]();
[Link](null,answer);
[Link](0);
}
}

You can also test the server with telnet.

A Capitalization Server and


Client
The server
[Link]
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
/**
*Aserverprogramwhichacceptsrequestsfromclientsto
*[Link],anewthreadis
*startedtohandleaninteractivedialoginwhichtheclient
*sendsinastringandtheserverthreadsendsbackthe
*capitalizedversionofthestring.
*
*Theprogramisrunsinaninfiniteloop,soshutdownin
platform
*[Link]
"java"
*interpreter,Ctrl+Cgenerallywillshutitdown.
*/
publicclassCapitalizeServer{
/**
*Applicationmethodtoruntheserverrunsinan
infiniteloop
*[Link]
requested,it

*spawnsanewthreadtodotheservicingandimmediately
returns
*[Link]
foreach
*clientthatconnectsjusttoshowinterestinglogging
*[Link].
*/
publicstaticvoidmain(String[]args)throwsException{
[Link]("Thecapitalizationserveris
running.");
intclientNumber=0;
ServerSocketlistener=newServerSocket(9898);
try{
while(true){
newCapitalizer([Link](),
clientNumber++).start();
}
}finally{
[Link]();
}
}
/**
*Aprivatethreadtohandlecapitalizationrequestsona
particular
*[Link]
asingleline
*containingonlyaperiod.
*/
privatestaticclassCapitalizerextendsThread{
privateSocketsocket;
privateintclientNumber;
publicCapitalizer(Socketsocket,intclientNumber){
[Link]=socket;
[Link]=clientNumber;
log("Newconnectionwithclient#"+clientNumber
+"at"+socket);
}

/**
*Servicesthisthread'sclientbyfirstsendingthe
*clientawelcomemessagethenrepeatedlyreading
strings
*andsendingbackthecapitalizedversionofthe
string.
*/
publicvoidrun(){
try{
//Decoratethestreamssowecansend
characters
//[Link]
flushed
//aftereverynewline.
BufferedReaderin=newBufferedReader(
new
InputStreamReader([Link]()));
PrintWriterout=
newPrintWriter([Link](),
true);
//Sendawelcomemessagetotheclient.
[Link]("Hello,youareclient#"+
clientNumber+".");
[Link]("Enteralinewithonlyaperiod
toquit\n");
//Getmessagesfromtheclient,linebyline;
returnthem
//capitalized
while(true){
Stringinput=[Link]();
if(input==null||[Link](".")){
break;
}
[Link]([Link]());
}
}catch(IOExceptione){
log("Errorhandlingclient#"+clientNumber+

":"+e);
}finally{
try{
[Link]();
}catch(IOExceptione){
log("Couldn'tcloseasocket,what'sgoing
on?");
}
log("Connectionwithclient#"+clientNumber
+"closed");
}
}
/**
*[Link]
the
*messagetotheserverapplicationsstandardoutput.
*/
privatevoidlog(Stringmessage){
[Link](message);
}
}
}

The client
[Link]
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];

[Link];
[Link];
[Link];
[Link];
/**
*AsimpleSwingbasedclientforthecapitalizationserver.
*Ithasamainframewindowwithatextfieldforentering
*stringsandatextareatoseetheresultsofcapitalizing
*them.
*/
publicclassCapitalizeClient{
privateBufferedReaderin;
privatePrintWriterout;
privateJFrameframe=newJFrame("CapitalizeClient");
privateJTextFielddataField=newJTextField(40);
privateJTextAreamessageArea=newJTextArea(8,60);
/**
*ConstructstheclientbylayingouttheGUIand
registeringa
*listenerwiththetextfieldsothatpressingEnterin
the
*listenersendsthetextfieldcontentstotheserver.
*/
publicCapitalizeClient(){
//LayoutGUI
[Link](false);
[Link]().add(dataField,"North");
[Link]().add(new
JScrollPane(messageArea),"Center");
//AddListeners
[Link](newActionListener(){
/**
*Respondstopressingtheenterkeyinthe
textfield
*bysendingthecontentsofthetextfieldto

the
*serveranddisplayingtheresponsefromthe
server
*[Link]"."we
exit
*thewholeapplication,whichclosesall
sockets,
*streamsandwindows.
*/
publicvoidactionPerformed(ActionEvente){
[Link]([Link]());
Stringresponse;
try{
response=[Link]();
if(response==null||
[Link]("")){
[Link](0);
}
}catch(IOExceptionex){
response="Error:"+ex;
}
[Link](response+"\n");
[Link]();
}
});
}
/**
*Implementstheconnectionlogicbypromptingtheend
userfor
*theserver'sIPaddress,connecting,settingup
streams,and
*[Link]
Capitalizer
*protocolsaysthattheserversendsthreelinesoftext
tothe
*clientimmediatelyafterestablishingaconnection.
*/
publicvoidconnectToServer()throwsIOException{

//Gettheserveraddressfromadialogbox.
StringserverAddress=[Link](
frame,
"EnterIPAddressoftheServer:",
"WelcometotheCapitalizationProgram",
JOptionPane.QUESTION_MESSAGE);
//Makeconnectionandinitializestreams
Socketsocket=newSocket(serverAddress,9898);
in=newBufferedReader(
new
InputStreamReader([Link]()));
out=newPrintWriter([Link](),true);
//Consumetheinitialwelcomingmessagesfromthe
server
for(inti=0;i<3;i++){
[Link]([Link]()+"\n");
}
}
/**
*Runstheclientapplication.
*/
publicstaticvoidmain(String[]args)throwsException{
CapitalizeClientclient=newCapitalizeClient();

[Link](JFrame.EXIT_ON_CLOSE);
[Link]();
[Link](true);
[Link]();
}
}

A Two-Player Networked TicTac-Toe Game


The server

[Link]
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
/**
*Aserverforanetworkmultiplayertictactoegame.
Modifiedand
*extendedfromtheclasspresentedinDeitelandDeitel
"JavaHowto
*Program"[Link]
largesections
*[Link]*data*
betweenthe
*clientandserver,ImadeaTTTP(tictactoeprotocol)
whichistotally
*plaintext,soyoucantestthegamewithTelnet(alwaysa
goodidea.)
*ThestringsthataresentinTTTPare:
*
*Client>ServerServer>Client
*
*MOVE<n>(0<=n<=8)WELCOME<char>(charin{X,
O})
*QUITVALID_MOVE
*OTHER_PLAYER_MOVED<n>
*VICTORY
*DEFEAT
*TIE
*MESSAGE<text>
*
*Asecondchangeisthatitallowsanunlimitednumberof
pairsof
*playerstoplay.

*/
publicclassTicTacToeServer{
/**
*[Link].
*/
publicstaticvoidmain(String[]args)throwsException{
ServerSocketlistener=newServerSocket(8901);
[Link]("TicTacToeServerisRunning");
try{
while(true){
Gamegame=newGame();
[Link]=[Link]
Player([Link](),'X');
[Link]=[Link]
Player([Link](),'O');
[Link](playerO);
[Link](playerX);
[Link]=playerX;
[Link]();
[Link]();
}
}finally{
[Link]();
}
}
}
/**
*Atwoplayergame.
*/
classGame{
/**
*[Link]
unownedor
*[Link]
player
*[Link],thecorrespondingsquareis
unowned,

*otherwisethearraycellstoresareferencetothe
playerthat
*ownsit.
*/
privatePlayer[]board={
null,null,null,
null,null,null,
null,null,null};
/**
*Thecurrentplayer.
*/
PlayercurrentPlayer;
/**
*Returnswhetherthecurrentstateoftheboardissuch
thatone
*oftheplayersisawinner.
*/
publicbooleanhasWinner(){
return
(board[0]!=null&&board[0]==board[1]&&
board[0]==board[2])
||(board[3]!=null&&board[3]==board[4]&&
board[3]==board[5])
||(board[6]!=null&&board[6]==board[7]&&
board[6]==board[8])
||(board[0]!=null&&board[0]==board[3]&&
board[0]==board[6])
||(board[1]!=null&&board[1]==board[4]&&
board[1]==board[7])
||(board[2]!=null&&board[2]==board[5]&&
board[2]==board[8])
||(board[0]!=null&&board[0]==board[4]&&
board[0]==board[8])
||(board[2]!=null&&board[2]==board[4]&&
board[2]==board[6]);
}
/**

*Returnswhethertherearenomoreemptysquares.
*/
publicbooleanboardFilledUp(){
for(inti=0;i<[Link];i++){
if(board[i]==null){
returnfalse;
}
}
returntrue;
}
/**
*Calledbytheplayerthreadswhenaplayertriesto
makea
*[Link]:
that
*is,theplayerrequestingthemovemustbethecurrent
player
*andthesquareinwhichsheistryingtomovemustnot
already
*[Link]
updated
*(thesquareissetandthenextplayerbecomescurrent)
and
*theotherplayerisnotifiedofthemovesoitcan
updateits
*client.
*/
publicsynchronizedbooleanlegalMove(intlocation,Player
player){
if(player==currentPlayer&&board[location]==
null){
board[location]=currentPlayer;
currentPlayer=[Link];
[Link](location);
returntrue;
}
returnfalse;
}

/**
*Theclassforthehelperthreadsinthismultithreaded
server
*[Link]
mark
*whichiseither'X'or'O'.Forcommunicationwiththe
*clienttheplayerhasasocketwithitsinputand
output
*[Link]
a
*readerandawriter.
*/
classPlayerextendsThread{
charmark;
Playeropponent;
Socketsocket;
BufferedReaderinput;
PrintWriteroutput;
/**
*Constructsahandlerthreadforagivensocketand
mark
*initializesthestreamfields,displaysthefirst
two
*welcomingmessages.
*/
publicPlayer(Socketsocket,charmark){
[Link]=socket;
[Link]=mark;
try{
input=newBufferedReader(
new
InputStreamReader([Link]()));
output=new
PrintWriter([Link](),true);
[Link]("WELCOME"+mark);
[Link]("MESSAGEWaitingforopponent
toconnect");
}catch(IOExceptione){
[Link]("Playerdied:"+e);

}
}
/**
*Acceptsnotificationofwhotheopponentis.
*/
publicvoidsetOpponent(Playeropponent){
[Link]=opponent;
}
/**
*HandlestheotherPlayerMovedmessage.
*/
publicvoidotherPlayerMoved(intlocation){
[Link]("OPPONENT_MOVED"+location);
[Link](
hasWinner()?"DEFEAT":boardFilledUp()?
"TIE":"");
}
/**
*Therunmethodofthisthread.
*/
publicvoidrun(){
try{
//Thethreadisonlystartedaftereveryone
connects.
[Link]("MESSAGEAllplayers
connected");
//Tellthefirstplayerthatitisherturn.
if(mark=='X'){
[Link]("MESSAGEYourmove");
}
//Repeatedlygetcommandsfromtheclientand
processthem.
while(true){
Stringcommand=[Link]();
if([Link]("MOVE")){

intlocation=
[Link]([Link](5));
if(legalMove(location,this)){
[Link]("VALID_MOVE");
[Link](hasWinner()?
"VICTORY"
:boardFilledUp()?
"TIE"
:"");
}else{
[Link]("MESSAGE?");
}
}elseif([Link]("QUIT")){
return;
}
}
}catch(IOExceptione){
[Link]("Playerdied:"+e);
}finally{
try{[Link]();}catch(IOExceptione){}
}
}
}
}

The client
[Link]
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];

[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
/**
*AclientfortheTicTacToegame,modifiedandextendedfrom
the
*classpresentedinDeitelandDeitel"JavaHowtoProgram"
book.
*Imadeabunchofenhancementsandrewrotelargesections
ofthe
*[Link](TicTacToe
Protocol)
*[Link]
aresent:
*
*Client>ServerServer>Client
*
*MOVE<n>(0<=n<=8)WELCOME<char>(charin{X,
O})
*QUITVALID_MOVE
*OTHER_PLAYER_MOVED<n>
*VICTORY
*DEFEAT
*TIE
*MESSAGE<text>
*
*/
publicclassTicTacToeClient{
privateJFrameframe=newJFrame("TicTacToe");
privateJLabelmessageLabel=newJLabel("");
privateImageIconicon;
privateImageIconopponentIcon;
privateSquare[]board=newSquare[9];

privateSquarecurrentSquare;
privatestaticintPORT=8901;
privateSocketsocket;
privateBufferedReaderin;
privatePrintWriterout;
/**
*Constructstheclientbyconnectingtoaserver,laying
outthe
*GUIandregisteringGUIlisteners.
*/
publicTicTacToeClient(StringserverAddress)throws
Exception{
//Setupnetworking
socket=newSocket(serverAddress,PORT);
in=newBufferedReader(newInputStreamReader(
[Link]()));
out=newPrintWriter([Link](),true);
//LayoutGUI
[Link]([Link]);
[Link]().add(messageLabel,"South");
JPanelboardPanel=newJPanel();
[Link]([Link]);
[Link](newGridLayout(3,3,2,2));
for(inti=0;i<[Link];i++){
finalintj=i;
board[i]=newSquare();
board[i].addMouseListener(newMouseAdapter(){
publicvoidmousePressed(MouseEvente){
currentSquare=board[j];
[Link]("MOVE"+j);}});
[Link](board[i]);
}
[Link]().add(boardPanel,"Center");
}

/**
*Themainthreadoftheclientwilllistenformessages
*[Link]"WELCOME"
*[Link]
a
*looplisteningfor"VALID_MOVE","OPPONENT_MOVED",
"VICTORY",
*"DEFEAT","TIE","OPPONENT_QUITor"MESSAGE"messages,
*[Link]
"VICTORY",
*"DEFEAT"and"TIE"asktheuserwhetherornottoplay
*[Link],theloopisexited
and
*theserverissenta"QUIT"[Link]
OPPONENT_QUIT
*messageisreceviedthentheloopwillexitandthe
server
*willbesenta"QUIT"messagealso.
*/
publicvoidplay()throwsException{
Stringresponse;
try{
response=[Link]();
if([Link]("WELCOME")){
charmark=[Link](8);
icon=newImageIcon(mark=='X'?"[Link]":
"[Link]");
opponentIcon=newImageIcon(mark=='X'?
"[Link]":"[Link]");
[Link]("TicTacToePlayer"+
mark);
}
while(true){
response=[Link]();
if([Link]("VALID_MOVE")){
[Link]("Validmove,please
wait");
[Link](icon);
[Link]();
}elseif

([Link]("OPPONENT_MOVED")){
intloc=
[Link]([Link](15));
board[loc].setIcon(opponentIcon);
board[loc].repaint();
[Link]("Opponentmoved,your
turn");
}elseif([Link]("VICTORY")){
[Link]("Youwin");
break;
}elseif([Link]("DEFEAT")){
[Link]("Youlose");
break;
}elseif([Link]("TIE")){
[Link]("Youtied");
break;
}elseif([Link]("MESSAGE")){

[Link]([Link](8));
}
}
[Link]("QUIT");
}
finally{
[Link]();
}
}
privatebooleanwantsToPlayAgain(){
intresponse=[Link](frame,
"Wanttoplayagain?",
"TicTacToeisFunFunFun",
JOptionPane.YES_NO_OPTION);
[Link]();
returnresponse==JOptionPane.YES_OPTION;
}
/**
*[Link]
*[Link]()to

fill
*itwithanIcon,presumablyanXorO.
*/
staticclassSquareextendsJPanel{
JLabellabel=newJLabel((Icon)null);
publicSquare(){
setBackground([Link]);
add(label);
}
publicvoidsetIcon(Iconicon){
[Link](icon);
}
}
/**
*Runstheclientasanapplication.
*/
publicstaticvoidmain(String[]args)throwsException{
while(true){
StringserverAddress=([Link]==0)?
"localhost":args[1];
TicTacToeClientclient=new
TicTacToeClient(serverAddress);

[Link](JFrame.EXIT_ON_CLOSE);
[Link](240,160);
[Link](true);
[Link](false);
[Link]();
if(![Link]()){
break;
}
}
}
}

A Multi-User Chat Application

The server
[Link]
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
/**
*[Link]
the
*serverrequestsascreennamebysendingtheclientthe
*text"SUBMITNAME",andkeepsrequestinganameuntil
*[Link]
*name,theserveracknowledgeswith"NAMEACCEPTED".Then
*allmessagesfromthatclientwillbebroadcasttoall
other
*[Link]
*broadcastmessagesareprefixedwith"MESSAGE".
*
*Becausethisisjustateachingexampletoillustratea
simple
*chatserver,thereareafewfeaturesthathavebeenleft
out.
*Twoareveryusefulandbelonginproductioncode:
*
*[Link]
can
*sendcleandisconnectmessagestotheserver.
*
*[Link].
*/
publicclassChatServer{

/**
*Theportthattheserverlistenson.
*/
privatestaticfinalintPORT=9001;
/**
*Thesetofallnamesofclientsinthechatroom.
Maintained
*sothatwecancheckthatnewclientsarenot
registeringname
*alreadyinuse.
*/
privatestaticHashSet<String>names=new
HashSet<String>();
/**
*Thesetofalltheprintwritersforalltheclients.
This
*setiskeptsowecaneasilybroadcastmessages.
*/
privatestaticHashSet<PrintWriter>writers=new
HashSet<PrintWriter>();
/**
*Theappplicationmainmethod,whichjustlistensona
portand
*spawnshandlerthreads.
*/
publicstaticvoidmain(String[]args)throwsException{
[Link]("Thechatserverisrunning.");
ServerSocketlistener=newServerSocket(PORT);
try{
while(true){
newHandler([Link]()).start();
}
}finally{
[Link]();
}
}

/**
*[Link]
listening
*loopandareresponsibleforadealingwithasingle
client
*andbroadcastingitsmessages.
*/
privatestaticclassHandlerextendsThread{
privateStringname;
privateSocketsocket;
privateBufferedReaderin;
privatePrintWriterout;
/**
*Constructsahandlerthread,squirrelingawaythe
socket.
*Alltheinterestingworkisdoneintherunmethod.
*/
publicHandler(Socketsocket){
[Link]=socket;
}
/**
*Servicesthisthread'sclientbyrepeatedly
requestinga
*screennameuntilauniqueonehasbeensubmitted,
then
*acknowledgesthenameandregisterstheoutput
streamfor
*theclientinaglobalset,thenrepeatedlygets
inputsand
*broadcaststhem.
*/
publicvoidrun(){
try{
//Createcharacterstreamsforthesocket.
in=newBufferedReader(newInputStreamReader(
[Link]()));
out=new

PrintWriter([Link](),true);
//[Link]
requestinguntil
//anameissubmittedthatisnotalready
[Link]
//checkingfortheexistenceofanameand
addingthename
//mustbedonewhilelockingthesetof
names.
while(true){
[Link]("SUBMITNAME");
name=[Link]();
if(name==null){
return;
}
synchronized(names){
if(![Link](name)){
[Link](name);
break;
}
}
}
//Nowthatasuccessfulnamehasbeenchosen,
addthe
//socket'sprintwritertothesetofall
writersso
//thisclientcanreceivebroadcastmessages.
[Link]("NAMEACCEPTED");
[Link](out);
//Acceptmessagesfromthisclientand
broadcastthem.
//Ignoreotherclientsthatcannotbe
broadcastedto.
while(true){
Stringinput=[Link]();
if(input==null){
return;

}
for(PrintWriterwriter:writers){
[Link]("MESSAGE"+name+":
"+input);
}
}
}catch(IOExceptione){
[Link](e);
}finally{
//Thisclientisgoingdown!Removeitsname
anditsprint
//writerfromthesets,andcloseitssocket.
if(name!=null){
[Link](name);
}
if(out!=null){
[Link](out);
}
try{
[Link]();
}catch(IOExceptione){
}
}
}
}
}

The client
[Link]
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];

[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
/**
*AsimpleSwingbasedclientforthechatserver.
Graphically
*itisaframewithatextfieldforenteringmessagesanda
*textareatoseethewholedialog.
*
*TheclientfollowstheChatProtocolwhichisasfollows.
*Whentheserversends"SUBMITNAME"theclientreplieswith
the
*[Link]
"SUBMITNAME"
*requestsaslongastheclientsubmitsscreennamesthat
are
*[Link]
*with"NAMEACCEPTED"theclientisnowallowedtostart
*sendingtheserverarbitrarystringstobebroadcasttoall
*[Link]
*linebeginningwith"MESSAGE"thenallcharacters
following
*thisstringshouldbedisplayedinitsmessagearea.
*/
publicclassChatClient{
BufferedReaderin;
PrintWriterout;
JFrameframe=newJFrame("Chatter");
JTextFieldtextField=newJTextField(40);
JTextAreamessageArea=newJTextArea(8,40);
/**
*ConstructstheclientbylayingouttheGUIand
registeringa

*listenerwiththetextfieldsothatpressingReturnin
the
*listenersendsthetextfieldcontentstotheserver.
Note
*howeverthatthetextfieldisinitiallyNOTeditable,
and
*onlybecomeseditableAFTERtheclientreceivesthe
NAMEACCEPTED
*messagefromtheserver.
*/
publicChatClient(){
//LayoutGUI
[Link](false);
[Link](false);
[Link]().add(textField,"North");
[Link]().add(new
JScrollPane(messageArea),"Center");
[Link]();
//AddListeners
[Link](newActionListener(){
/**
*Respondstopressingtheenterkeyinthe
textfieldbysending
*thecontentsofthetextfieldtotheserver.
Thenclear
*thetextareainpreparationforthenext
message.
*/
publicvoidactionPerformed(ActionEvente){
[Link]([Link]());
[Link]("");
}
});
}
/**
*Promptforandreturntheaddressoftheserver.
*/

privateStringgetServerAddress(){
[Link](
frame,
"EnterIPAddressoftheServer:",
"WelcometotheChatter",
JOptionPane.QUESTION_MESSAGE);
}
/**
*Promptforandreturnthedesiredscreenname.
*/
privateStringgetName(){
[Link](
frame,
"Chooseascreenname:",
"Screennameselection",
JOptionPane.PLAIN_MESSAGE);
}
/**
*Connectstotheserverthenenterstheprocessingloop.
*/
privatevoidrun()throwsIOException{
//Makeconnectionandinitializestreams
StringserverAddress=getServerAddress();
Socketsocket=newSocket(serverAddress,9001);
in=newBufferedReader(newInputStreamReader(
[Link]()));
out=newPrintWriter([Link](),true);
//Processallmessagesfromserver,accordingtothe
protocol.
while(true){
Stringline=[Link]();
if([Link]("SUBMITNAME")){
[Link](getName());
}elseif([Link]("NAMEACCEPTED")){
[Link](true);
}elseif([Link]("MESSAGE")){

[Link]([Link](8)+"\n");
}
}
}
/**
*Runstheclientasanapplicationwithacloseable
frame.
*/
publicstaticvoidmain(String[]args)throwsException{
ChatClientclient=newChatClient();

[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
[Link]();
}
}

You might also like