help me in mulitclient of this applicaiton

hello every body,,,

i am a new contact to this forum, i am july doglas from USA..

i am working in this programe, i write a hangman game in client server architecture but when i try to convert it to multiple client i couldn't know how to do that!!

i want server connect to mulitple client and each new one start playing with the pervious clients ( not starting it's own game ),, i think that it's good to put an ordering between clients so there is turn for each one..

i hope i descripe my problem clearly, please help me as fast as you can

server codeimport java.io.*;

import java.net.*;

import java.awt.*;

publicclass Serverextends Object{

private ServerSocket server;// player connects through

// this socket

private Socket player;// socket to communicate

// with connected player

private DataInputStream input;// input stream associated

// with player socket

private DataOutputStream output;// output stream associated

//with player socket

// Constructor -- starts up service

public Server(){

try{

server =new ServerSocket( 4443, 1 );// port 443, one player

player = server.accept();// await the player; create player socket

server.close();// close service since only a one player game

// create input and output streams for player communication

input =new DataInputStream(player.getInputStream());

output =new DataOutputStream(player.getOutputStream());

}catch (IOException e){

e.printStackTrace();

System.exit(1);

}

}

// select a word randomly for a large dictionary

public String choose(){

String word ="";

try{

RandomAccessFile wordFile =new

RandomAccessFile("words.txt","r");

long pos = (long) (Math.random() * (wordFile.length() - 11));

wordFile.seek(pos);

wordFile.readLine();

word = wordFile.readLine().toUpperCase();

wordFile.close();

}catch (IOException e){

System.out.println("Error -- " + e.toString());

System.exit(1);

}

return word;

}

// build coded message sent back to player

// this tells player where correct guesses belong in word

// return true if player has won

publicboolean buildCode(String word,char letter,char[] codedWord){

boolean ok =false;

boolean win =true;

for (int i = 0, j = 2; i < word.length(); i++, j += 2 ){

if ((word.charAt(i)) == letter){

codedWord[j] = letter;// fill in correct choice

ok =true;

}elseif (codedWord[j] =='_'){

win =false;// at least one letter not yet found

}

}

if (ok) System.out.println("Good Guess!!!");

else System.out.println("Bad Guess!!!");

return win;

}

// this is where the real action occurs

publicvoid execute(){

try{

int badGuesses = 0;// no bad choices yet

String word = choose();// the magic word

// false components of usedChars represent

// potential new bad guesses

boolean usedChars[] =newboolean[26];

// make all componenest false

for (int i=0; i<26; i++){

usedChars[i] =false;

}

// change those associated with letters in word to true

// they're not bad guesses

for (int i=0; i < word.length(); i++){

usedChars[word.charAt(i)-'A'] =true;

}

// coded word

// codedWord[0] = char version of #of bad guesses

//codedWord[1] = 'P' if continue play

//'W' if player has won

//'L' is player has lost

//rest of codedWord indicates letters guessed correctly

char[] codedWord =newchar[22];

codedWord[0]='0';

codedWord[1]='P';

for (int j = 2; j < 22; j++){

codedWord[j]=' ';

}

for (int i = 0, j = 2; i < word.length(); i++, j += 2 ){

codedWord[j]='_';

}

// send string version of coded word to player

String temp =new String(codedWord, 0, 22);

System.out.println(temp +" - " + word);

output.writeUTF(temp);// actual write on socket

// play the game

boolean win =false;

// game goes until win or loss

while (!win && (badGuesses < 6)){

// get user letter choice, update badGuesses, if needed

System.out.println("Pick a letter: ");

char guess = Character.toUpperCase((char) input.readByte());

if (!usedChars[guess-'A']){

usedChars[guess-'A'] =true;

badGuesses++;

}

win = buildCode(word, guess, codedWord);

codedWord[0] = (char) ('0'+badGuesses);

if (win){

System.out.println("You win!!!");codedWord[1]='W';

}elseif (badGuesses >= 6){

System.out.println("You lose!!!");codedWord[1]='L';

}

// send code word back to player

temp =new String(codedWord, 0 ,22);

System.out.println(temp +" - "+word);

output.writeUTF(temp);

}

// be a good citizen, closing all open streams and sockets

input.close();

output.close();// this is real important since it flushes stream

player.close();

}catch (IOException e){ e.printStackTrace();}

}

// create server and start it up

publicstaticvoid main(String[] args){

Server hangman =new Server();

hangman.execute();

}

}

client code

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

import java.net.*;

import java.io.*;

publicclass clientextends Appletimplements Runnable, ActionListener{

Socket server;// socket created when connect to server

DataInputStream input;// input stream associated with

// server socket

DataOutputStream output;// output stream associated with

// server socket

// Start up by connecting to server and opening streams

Thread playerThread;// player runs in this thread

publicvoid start(){ System.out.println("start");

try{

server =new Socket(InetAddress.getLocalHost(), 4444);//server = new Socket("192.1.1.1", 443);//

input =new DataInputStream(server.getInputStream());

output =new DataOutputStream(server.getOutputStream());

}

catch( IOException e){ e.printStackTrace();}

playerThread =new Thread(this );

playerThread.start();

System.out.println("start thread");

}

// Just start up method that monitors communication from server

publicvoid run(){System.out.println("run");

play();

}

boolean laugh =false;// start with flush; laugh next time

boolean firstTime =true;// first time we call sound method

// Play sounds appropriate to user's last selection

void playsound(char previousWrong,char newWrong){

if (newWrong > previousWrong){// variety on razzing

if (laugh) play(getCodeBase(),"audio/laugh.au");

else play(getCodeBase(),"audio/flush.au");

}elseif (!firstTime)

play(getCodeBase(),"audio/excellent.au");

laugh = !laugh;// toggle between laugh and flushing sound

firstTime =false;// recall we've been here before

}

String word ="";// partial word

String message ="Choose a letter!";// encourage player

// Play the game

void play(){System.out.println("play");

play(getCodeBase(),"audio/playgame.au");

char previousIncorrect ='0';

char result ='P';

try{

int num=input.readInt();

System.out.println(num);

while (result =='P'){

String line = input.readUTF();

word = line.substring(2, line.length()-2);

result = line.charAt(1);

char incorrectGuesses = line.charAt(0);

image = images[Character.digit(incorrectGuesses, 10)];

repaint();

playsound(previousIncorrect, incorrectGuesses);

previousIncorrect = incorrectGuesses;

}

if (result =='W'){

message ="Congratulations, You WIN!!!";

play(getCodeBase(),"audio/woohoo.au");

}else{

message ="Ha, Ha, You Lose!!!";

play(getCodeBase(),"audio/darn.au");

}

repaint();

input.close();

output.close();

server.close();

}catch(IOException e){

e.printStackTrace();

System.exit(1);

}

}

// Get images (hangman) and create letter buttons

Button[] alpha =new Button[26];// letter buttons

Image image;// current hangman image

Image[] images =new Image[7];// collection of hangman images

publicvoid init(){

setBackground(Color.white);

images[0] = getImage(getCodeBase(),"images/hman0.gif");

images[1] = getImage(getCodeBase(),"images/hman1.gif");

images[2] = getImage(getCodeBase(),"images/hman2.gif");

images[3] = getImage(getCodeBase(),"images/hman3.gif");

images[4] = getImage(getCodeBase(),"images/hman4.gif");

images[5] = getImage(getCodeBase(),"images/hman5.gif");

images[6] = getImage(getCodeBase(),"images/hman6.gif");

image = images[0];

Panel p1 =new Panel();

p1.setLayout(new GridLayout(2, 13, 1, 1));

for (int i = 0; i <26; i++){

alpha[i] =new Button((new Character((char)('A'+i))).toString());

p1.add(alpha[i]); alpha[i].addActionListener(this);

}

add("North", p1);

}

// Handle letter selections

publicvoid actionPerformed(ActionEvent e){

try{

char command = e.getActionCommand().charAt(0);

output.writeByte(command);// report letter to server

// don't allow this one to be selected again

alpha[command-'A'].setEnabled(false);

}catch (IOException ev){

ev.printStackTrace();

}

}

// refresh screen with word

publicvoid paint(Graphics g){

g.setFont(new Font("TimesRoman", Font.BOLD, 18));

g.setColor(Color.black);

g.drawString(word, 270, 140);

g.drawString(message, 270, 80);

g.drawImage(image, 60, 150, Color.white,this);

}

}

[20553 byte] By [july_doglasa] at [2007-11-26 14:14:22]
# 1

couldnt you post a bigger post? Anyway you need to change the design of your server.

You need to use threads.

The serverMainClass have to listen to new conenctions, once it receive a new connection it needs to pass it to another slave socket that concurrently must run and attend the service.

I made a server on that way for a game I was doing maybe later I could send you the code.

MelGohana at 2007-7-8 2:03:46 > top of Java-index,Core,Core APIs...
# 2

Thank you MelGohan, but i try to change the design of both server and the client but i fail, my idea is to make every client connect to a socket then when every client guess a letter the result send back to server and the second send it a gain to next client in turn, and so on. i try to make my idea similar to an example of tictacto game in dietl book at chaper 17.

july_doglasa at 2007-7-8 2:03:46 > top of Java-index,Core,Core APIs...
# 3

I defined a ServerThread and an Atention class.

the serverThreads manage the connections form the clients and the Atention class represents the atention given to the client. Here is the code, it works for me but has many thing usless for your project, try to understand it and make your own. Also feel free to use the code as you wish. I better will delete the useless part of the ServerThread

public class ServerThread extends Thread{

ServerSocket Maestro;

boolean salida;

/** Creates new ServerThread */

public ServerThread(World Ju) {

salida=false;

try {

Maestro=new ServerSocket (8888);

} catch (Exception E) {

System.out.println ("Error creando el ServerSocket");

E.printStackTrace ();

}

}

public void run () {

while (!salida) {

System.out.println ("El servidor esta atendiendo");

Socket cliente=null;

try {

cliente=Maestro.accept ();

System.out.println ("Atencion solicitada");

} catch (Exception E) {

System.out.println ("Error al aceptar la conexion");

E.printStackTrace();

}

if (cliente!=null){

Atencion personal=new Atencion (cliente, jugadores);

personal.setPriority (Thread.MAX_PRIORITY);

personal.start ();

}

}

}

public void salir () {

salida=true;

}

}

With this srver implementation each client will be attended concurrently and for shared information you can use the ServerThread class and some references.

MelGohana at 2007-7-8 2:03:46 > top of Java-index,Core,Core APIs...