Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

problem with applet ....

1 view
Skip to first unread message

Andrew Skouloudis

unread,
Dec 30, 2003, 12:33:40 PM12/30/03
to
I am trying to create a simple applet for two playes (MineSweeper )
using a server-client scheme . The problem is that I cannot make both
the server and the client to create a new game (in the final version
of the pogram the client and the server play on the same board but
that is not the problem now ).

Using the following code i can make the client start a game but not
the server :


Server Code :

import java.applet.Applet;
import java.util.Random ;
import java.awt.*;
import java.net.*;
import java.io.*;

// Working version of first time execfution of the applet

public class SimpleServer extends Applet {

private Image[] img;
private Image buffer;
private Graphics Screen;
private String param;
private int[][] matrix;
private int[][] Board;
private int iX;
private int iY;
private int x_click;
private int y_click;
private int BoardcolSize;
private int BoardrowSize;
private int totalMines;
private int mineCount;
private boolean lost;
private boolean won;
private int correctFlags;
private int totalFlags;
ServerSocket server=null;
Socket clientSocket=null;
DataInputStream s_in = null;
DataOutputStream s_out = null;

public void init()
{


param = getParameter("bImg");

img=new Image[13];

for (int i = 0 ; i < 13 ; i++)
{
img[i] = getImage(getCodeBase(), param + (i) +
".gif");
}

try
{
ConnectOnSocket();
}
catch (IOException e)
{
System.exit(-1);
}

StartNewGame();
}

public void ConnectOnSocket() throws IOException
{
try
{
server = new ServerSocket(9999);
}
catch (IOException e)
{
// ServerSocket failed
}

try
{
clientSocket = server.accept();
}
catch (IOException e)
{
// Socket failed !!
}

s_out = new DataOutputStream(clientSocket.getOutputStream());
s_in = new
DataInputStream(clientSocket.getInputStream());

}


public void StartNewGame()
{

BoardcolSize=5;
BoardrowSize=5;
totalMines=2;
mineCount=0;
won=false;
lost=false;
totalFlags=0;
correctFlags=0;
Board =new int[BoardrowSize][BoardcolSize];
CreateBoard();

matrix=new int[BoardrowSize][BoardcolSize];
iX=0;
iY=0;
for(int j=0; j<BoardrowSize; j++)
{
for(int k=0; k<BoardcolSize; k++)
{
matrix[j][k]=10;
}
}
repaint();
}



public void start()
{
repaint();
}

public void paint(Graphics g)
{
update(g);
}
public void CreateBoard()
{
int minesSet=0;
// Random x_generator = new Random();
// Random y_generator = new Random();
Random rand_generator = new Random();
int x_mine,y_mine;
int adj_mines=0;

//First of all fill the Board with default image value
...
for(int z=0; z<BoardrowSize; z++)
{
for (int k=0; k<BoardcolSize; k++)
{
Board[z][k]=0;
}
}
// Secondly , fill the board with totalMines mines...
while(minesSet != totalMines)
{
x_mine=rand_generator.nextInt(BoardrowSize);
y_mine=rand_generator.nextInt(BoardcolSize);
if(Board[x_mine][y_mine] == 0)
{
Board[x_mine][y_mine]=9;
minesSet=minesSet+1;
}
}

// Finally fill the rest of the board with the numbers
of the adjacent matrix ..
for(int i=0; i<BoardrowSize; i++)
{
for(int j=0; j<BoardcolSize; j++)
{
if(Board[i][j]==0) {
if((i-1)>=0)
{
if((j-1)>=0)
{
if(Board[i-1][j-1]==9)
adj_mines++;
}
if(Board[i-1][j]==9) adj_mines++;
if((j+1) < BoardcolSize)
{
if(Board[i-1][j+1]==9)
adj_mines++;
}
}
if((i+1)<BoardrowSize)
{
if((j-1)>=0)
{
if(Board[i+1][j-1]==9)
adj_mines++;
}
if(Board[i+1][j]==9)
adj_mines++;
if((j+1)<BoardrowSize)
{
if(Board[i+1][j+1]==9)
adj_mines++;
}
}
if((j-1)>=0)
{
if(Board[i][j-1]==9)
adj_mines++;
}
if((j+1)<BoardcolSize)
{
if(Board[i][j+1]==9)
adj_mines++;
}
Board[i][j]=adj_mines;
adj_mines=0; }
}
}
} // end of double nest loop ...



public boolean mouseDown(Event evt, int x, int y)
{
/*int iC=(x-iX)/15;
int iL=(x-iY)/15;*/
x_click=(x-iX)/15;
y_click=(y-iY)/15;
if( (x_click <BoardrowSize) && (y_click <
BoardcolSize))
{
if(evt.metaDown())
{
if(matrix[x_click][y_click]==11)
{
matrix[x_click][y_click]=10;
totalFlags--;
if(Board[x_click][y_click]==9)
{
correctFlags--;
}
}
else
{
if( (matrix[x_click][y_click]
== 10) && (totalFlags<totalMines))
{

matrix[x_click][y_click]=11;
totalFlags++;
// Now it is time to
check if you have found a mine ...

if(Board[x_click][y_click]==9)
{

correctFlags++;
// if all
mines found and flagged

if(correctFlags==totalMines)
{

won=true;
}
}
}
}
}
else
{

matrix[x_click][y_click]=Board[x_click][y_click];
if(Board[x_click][y_click]==9)
{
lost=true;
}
}

}
repaint();
return true;
}


public synchronized void update(Graphics g)
{
/* if (offScreen!=null)
{
paintApplet(offScreen);
g.drawImage(buffer,0,0,this);
} else */
paintApplet(g);
} // end of update

public void paintApplet(Graphics g)
{
int i=0;
int j=0;
for(j=0; j<BoardrowSize; j++)
{
for(i=0; i<BoardcolSize; i++)
{
g.drawImage(img[matrix[j][i]], iX+(j*15), iY +
(i*15) , this);
}
}
g.drawString ("X: " + x_click + " Y: " + y_click, 59, 180);
if(won==true)
{
g.drawString("YOU ARE THE BEST !!! YOU WON ..",90,200);
StartNewGame();
}
if(lost==true) StartNewGame();
}
}


/////////////////////////////////////////////////////////////////////

Client code :

...........................................

public void init()
{


param = getParameter("bImg");

img=new Image[13];

for (int i = 0 ; i < 13 ; i++)
{
img[i] = getImage(getCodeBase(), param + (i) +
".gif");
}
try
{
ConnectOnSocket();
}
catch (IOException e)
{
System.exit(-1);
}
/* catch (UnknownHostException e)
{
System.exit(-1);
}*/
StartNewGame();
}
public void ConnectOnSocket() throws IOException
{
try
{
localhostSocket = new Socket("127.0.0.1", 9999);
s_out = new
DataOutputStream(localhostSocket.getOutputStream());
s_in = new
DataInputStream(localhostSocket.getInputStream());
}
catch (UnknownHostException e)
{
// UnknowHostException caught ..
}
catch (IOException e)
{
// IOException caught ..
}
}

...................................

I have put " .................... " because the code is the same with
the server except some initializations ...

Any help appreciated

(Sorry for my english .. )

Andrew Thompson

unread,
Dec 30, 2003, 7:21:09 PM12/30/03
to
"Andrew Skouloudis" <afterskoulN...@yahoo.com> wrote in message
news:58d3vvkrdvr32eqij...@4ax.com...

> I am trying to create a simple applet for two playes (MineSweeper )
> using a server-client scheme .

I do not have time at the moment to look at
your complete example, but a quick question..

What is the exact exception you are getting?

If it is a SecurityAccessException, the problem
might be the Applet security sandbox..

--
Andrew Thompson
* http://www.PhySci.org/ PhySci software suite
* http://www.1point1C.org/ 1.1C - Superluminal!
* http://www.AThompson.info/andrew/ personal site


Andrew Skouloudis

unread,
Dec 31, 2003, 3:11:35 AM12/31/03
to
On Wed, 31 Dec 2003 00:21:09 GMT, "Andrew Thompson"
<andr...@bigNOSPAMpond.com> wrote:

>"Andrew Skouloudis" <afterskoulN...@yahoo.com> wrote in message
>news:58d3vvkrdvr32eqij...@4ax.com...
>> I am trying to create a simple applet for two playes (MineSweeper )
>> using a server-client scheme .
>
>I do not have time at the moment to look at
>your complete example, but a quick question..
>
>What is the exact exception you are getting?
>
>If it is a SecurityAccessException, the problem
>might be the Applet security sandbox..

That's my problem : First of all i am new to Java programming (not to
programming generaly ) . Secondly i am trying to create a network
version of Minesweeper .... . I have created a one-palyer version of
the minesweeper working fine and i have created a simple text-based
client-server program that send some inegers between them .....
The problem is when i am trying to combine these programs , which
means to create the Server Applet that performs the same steps with
server program ( creates a ServerSocket , after a Client socket etc
...). and the Client applet that performs the same steps with the
Client program . In both applets inside the init function the
connectOnSocket function is called and what i am trying to do from the
ServerApplet side is to create a ServerSocket (called server ) then
to create a socket clientSocket that waits for a connection :

clientSocket = server.accept();

The ClientApplet is trying to connect to the Server using the usual
method , creates a socket and it tries to connect ..

localhostSocket = new Socket("127.0.0.1", 9999);

if all these steps were correct then after a connection is established
both SimpleServer applet and SimpleClient applet creates a new game
...

Now , I start the ServerApplet which won't do anything before
executing the client applet . Afterwards a start the SimpleClient
applet . Normally after the connection i must see two Boards in Both
Applets . I see a new Board in the SimpleClient applet , but I don't
see anything in the ServerApplet ..... ( I see a "x" ot a coffe-cup
sometimes .... )

Sorry for my english ...

Danny Woods

unread,
Dec 31, 2003, 4:23:35 AM12/31/03
to
Andrew Skouloudis <afterskoulN...@yahoo.com> writes:

> I am trying to create a simple applet for two playes (MineSweeper )
> using a server-client scheme . The problem is that I cannot make both
> the server and the client to create a new game (in the final version
> of the pogram the client and the server play on the same board but
> that is not the problem now ).
>
> Using the following code i can make the client start a game but not
> the server :
>

> localhostSocket = new Socket("127.0.0.1", 9999);

I'm dubious about this. Applets can only connect to the IP they were
served from, and can't even connect to localhost. If it were allowed,
two applets from unrelated servers could exchange information via
sockets by using the loopback address. That would be a security breach
waiting to happen.

Generally, expect SEVERE restrictions on networking in applets. Peer-to-peer
is simply not possible without digital signatures, which means that you'd
have to have some server side processing to allow a game at all. Each applet
could connect to the serving box and receive notification of events from
a CGI script or custom-written server app.

As a tip, when you catch exceptions, print it out to the console during
development. As Andrew Thompson says, you'll most likely find that it's a
security exception.

Regards,

Danny.

Andrew Skouloudis

unread,
Dec 31, 2003, 9:05:43 AM12/31/03
to
On 31 Dec 2003 09:23:35 +0000, Danny Woods
<no-mai...@black.hole.com> wrote:

Well i don't know if it is my lucky day but i managed finally to make
them communicate using the loopback 127.0.0.1 , Now the server can
send the board to the client . But i have a question here . I want
first the server to play and then to send the move to the client .
Once the client has received the data and have the board repainted,
he can play his move but not before that .The client cannot click on
the board unless he sees the move of his opponent in his board . How
can I do that ?? . How can I make the click event to have no effect on
the board before receiving the data from the server ????


Danny Woods

unread,
Dec 31, 2003, 10:03:19 AM12/31/03
to
Andrew Skouloudis <afterskoulN...@yahoo.com> writes:

Just have a boolean flag that your actionPerformed method can see,
indicating if it's your turn or not. Only do whatever the event handler's
written for if the flag indicates that it's your turn.

Are you writing and testing this with a real Web-server to hand? Which
browser/VM are you using?

Regards,

Danny.

Andrew Thompson

unread,
Dec 31, 2003, 10:39:51 AM12/31/03
to
"Andrew Skouloudis" <afterskoulN...@yahoo.com> wrote in message
news:8405vvkq3hrc0uv2f...@4ax.com...

> On Wed, 31 Dec 2003 00:21:09 GMT, "Andrew Thompson"
> <andr...@bigNOSPAMpond.com> wrote:
>
> >"Andrew Skouloudis" <afterskoulN...@yahoo.com> wrote in message
> >news:58d3vvkrdvr32eqij...@4ax.com...
> >> I am trying to create a simple applet for two playes (MineSweeper )
> >> using a server-client scheme .
> >
> >I do not have time at the moment to look at
> >your complete example, but a quick question..
> >
> >What is the exact exception you are getting?
> >
> >If it is a SecurityAccessException, the problem
> >might be the Applet security sandbox..
>
> That's my problem : First of all i am new to Java programming (not to
> programming generaly ) .

Java Console..

>..Secondly i am trying to create a network


> version of Minesweeper .... . I have created a one-palyer version of
> the minesweeper working fine and i have created a simple text-based
> client-server program that send some inegers between them .....
> The problem is when i am trying to combine these programs , which
> means to create the Server Applet that performs the same steps with
> server program ( creates a ServerSocket , after a Client socket etc
> ...). and the Client applet that performs the same steps with the
> Client program . In both applets inside the init function the
> connectOnSocket function is called and what i am trying to do from the
> ServerApplet side is to create a ServerSocket (called server ) then
> to create a socket clientSocket that waits for a connection :

OK. It seems you have some experience with
the networking, I will give you some advice.

Do _not_ do this as an Applet first, get
the GUI sorted out in an application,
but code the UI components within a
main Panel that can later be put in an Applet.
There is a good reason for this.

Applets are ..tricky. They are more difficult
to debug and develop, and have stringent
restrictions on what they are able to do.

I am not _certain_ if your example would
require a signed Applet in order to work
on a single machine, but it most certainly
will, to work between two.

Signing an Applet is no trivial matter,
eventually you will need to do it if you want to
have players working through a browser,
across the internet* but take one step at a time.

Get the GUI sorted, then come back to
the Applet.

* Though it is easier to dump the browser/applet
and do it between two apps.

_____________________________
In regards the specific problem at hand..

I compiled the server OK, but had problems
with the client. It said 'localhostSocket' was
missing, but I could not track it down.

Some more specific advice I can give you
in relation to applets, you need to find the
Java Console in your browser, it shows
all the error messages - (hey I could probably
advise you how to find it, but I don't think you
have mentioned your browser - another
comlication of applets)

And on _that_ note, you are 'swallowing' all
the exceptions! Catching them but not printing
anything out..

I suggest
catch ( Exception e ) { e.printStackTrace(); }

VERY handy..

> clientSocket = server.accept();
>
> The ClientApplet is trying to connect to the Server using the usual
> method , creates a socket and it tries to connect ..
>
> localhostSocket = new Socket("127.0.0.1", 9999);
>
> if all these steps were correct then after a connection is established
> both SimpleServer applet and SimpleClient applet creates a new game
> ...
>
> Now , I start the ServerApplet which won't do anything before
> executing the client applet .

That is a bad idea. Why not have the server
show the UI (buttons etc.), with a message,
'waiting for client' - or perhaps a modal
dialog if you really want to prevent the user
stuffing with the main UI will waiting.
Otherwise, the user knows nothing, and
gets frustrated very quickly.

I checked what the server would do when I
threw it in a web page - utterly blank square -
not very impressive.

> ...Afterwards a start the SimpleClient
> applet .

Add a text area to the server and let the
user know everything that is going on for the
moment - this is development, and we need
to see what is happening easily.

[ ..Don't lose hope, we'll get there! ]

Andrew Thompson

unread,
Dec 31, 2003, 10:53:56 AM12/31/03
to
"Danny Woods" <no-mai...@black.hole.com> wrote in message
news:867k0du...@khisanth.local...
> Andrew Skouloudis <afterskoulN...@yahoo.com> writes:
...

> have to have some server side processing to allow a game at all. Each
applet
> could connect to the serving box and receive notification of events from
> a CGI script or custom-written server app.

After notification of an appropriate
IP address, signed Applets should
be able to network directly to each
other - AFAIU.

Andrew Thompson

unread,
Dec 31, 2003, 4:20:20 PM12/31/03
to
"Andrew Skouloudis" <afterskoulN...@yahoo.com> wrote in message
news:8bl5vvs9ei2rh932g...@4ax.com...

> On 31 Dec 2003 09:23:35 +0000, Danny Woods
> <no-mai...@black.hole.com> wrote:
> >Andrew Skouloudis <afterskoulN...@yahoo.com> writes:
....

> >Generally, expect SEVERE restrictions on networking in applets.
Peer-to-peer
> >is simply not possible without digital signatures, which means that you'd
> >have to have some server side processing to allow a game at all.

..oops! missed that clarification
when I made my last post.

> >Danny.

Spot on.

> Well i don't know if it is my lucky

..hmmm

>...day but i managed finally to make


> them communicate using the loopback 127.0.0.1 , Now the server can
> send the board to the client . But i have a question here . I want
> first the server to play and then to send the move to the client .

What do you mean, move?

> Once the client has received the data and have the board repainted,
> he can play his move but not before that .The client cannot click on
> the board unless he sees the move of his opponent in his board .

What, are you saying you are sending the
entire graphic between server and client?

No!!

This would be so much simpler if I
could get your code to compile..

Passing the graphic between server and client
is not the way to do it, simply pass move details
between the two and have each draw it's own
screen.

>...How


> can I do that ?? . How can I make the click event to have no effect on
> the board before receiving the data from the server ????

How can you supply an SSCCE?
http://www.physci.org/codes/sscce.jsp
How can you do a GUI tutorial?
http://java.sun.com/docs/books/tutorial/uiswing/overview/event.html

Andrew Skouloudis

unread,
Jan 1, 2004, 10:13:59 AM1/1/04
to
First of all , I would like to wish everybody to have a happy new
year!.

Secondly , some background about the application.

I am working on Windows XP , the browser is Internet Explorer 6 and I
have installed
Sun's SDK version 1.4.2.
Some info about the minesweeper for one player :

Once a new game starts, the applet creates a new board ("Board"). A
new board is nothing more than a 2D array of integers with dimensions
BoardrowSize , BoardcolSize and it is created using the following
algorithm (function Createboard):

1.)First of all initialize the board with the value 10 (these values
are important I will explain later)
2.)Place the mines on the board (number of mines : totalmines) by
creating a random pair of integers (x,y) with limits the
the size of the board
3.)After that place in each point(that is not a mine) the number of
its adjacent mines.If a point (i,j) has not a mine
next to it , the value of this point remains as initialized at the
beggining

After that board is created,another board is created called "matrix"
and it is the board that the player sees in the player applet.
All the points of this board are initialized with a value of ten.
Actually this board (the "matrix") when you start a new game ,looks
exactly
the same with the initial look of the board in the original
minesweeper in Windows games ....

Now , when you press a box on the "matrix" then it's value becomes
equal with the value of the
corresponding point of the "Board" and when the applet is repainted ,
the "matrix" is printed but now the
box you pressed is revealed according to the value exists in the
"Board" .
But you don't see integers you see pictures . Here is a small trick ..
.Inside a folder called img are
various small images , another image for mine ,another for flag etc
... These images when the applets starts
are loaded into a array of images :

param = getParameter("bImg");

img=new Image[13];

for (int i = 0 ; i < 13 ; i++)
{
img[i] = getImage(getCodeBase(), param + (i) + ".gif");
}

so ..

j9.gif corresponds to a mine
j0.gif corresponds to an empty box
j11.gif corresponds to a flag etc .....

I think that it is now obvious how you play ... Just see the following
code :

for(j=0; j<BoardrowSize; j++)
{
for(i=0; i<BoardcolSize; i++)
{
g.drawImage(img[matrix[j][i]], iX+(j*15), iY + (i*15)
, this);
}
}

You just draw Images according the values of the "matrix" board . A
simple example

Suppose that the first line of the "matrix" is :
0,0,0,1,1,1,4,5,9

The first line of images that will be printed is :

image[0] image[0] image[0] image[1] image[1] image[1] image[4]
image[5] image[9]

or ...

empty box,empty box,empty box,one,one,one,four,four,five,mine

Of course you cannot see anything if you don't have the Img folder
...

Lets go now the network version ...

After you have created sockets etc,the server creates a board as I
discribed above and then
Server sends the board to the client (I have managed to write that).
When I say that the server
sends the board to the client I mean that the server sends integers
and of course not images..
Now here is my problem : I don't want the client(or the server) to be
able to play (that is to click on a box
and change the board ) until he sees the box that his opponent
revealed. Example when the
game begins, its server turn by default :

--> The server clicks a box on his board (i,j), the client cannot
click on his board
--> The "matrix" is repainted at servers applet,the client cannot
click on his board
--> The server sends two integers (i,j) to the client,the client
cannot click on his board
--> The client receives these two integers (i,j) ,the client cannot
click on his board
--> The "matrix" is repainted at clients applet,the client cannot
click on his board
--> The client clicks on his board (l,m) , the server cannot click on
his board
..............
..............
..............

I know that my English is awfull but it s clear what i have done and
what not ..


you can download here the images and the source code :
http://users.ntua.gr/el99063/java.zip

Note : mr Tompson and mr Woods i wrote down your remarks but I am
trying to make one step at a time , Java is different from C/C++ that
I have learned !!





Andrew Thompson

unread,
Jan 1, 2004, 5:52:14 PM1/1/04
to
"Andrew Skouloudis" <afterskoulN...@yahoo.com> wrote in message
news:46e8vvgh50qret2bd...@4ax.com...

> First of all , I would like to wish everybody to have a happy new
> year!.
>
> Secondly , some background about the application.

Since I am about to go to bed I skipped
the long post and cut straigh to this bit..

> you can download here the images and the source code :
> http://users.ntua.gr/el99063/java.zip

Aha! (at last!)

You still have not put 'e.printStackTrace();' in
all your 'catch' parts, so I did.

When I compiled it, I found you have used
'deprecated' api's, try..

javac -deprecation *.java

..for details.

Also, it is throwing exceptions. Once
you put in the 'e.printStackTrace()', the
Java Console will show things like..

java.net.BindException: Address already in use: JVM_Bind
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at SimpleServer2.ConnectOnSocket(SimpleServer2.java:64)
at SimpleServer2.init(SimpleServer2.java:49)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
at SimpleServer2.ConnectOnSocket(SimpleServer2.java:74)
at SimpleServer2.init(SimpleServer2.java:49)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

In internet explorer you can see the Java Console
under the menu..
Tools | Sun Java Console
this console not only shows the errors and 'print out',
but you can also use it to 'flush' an old version
of the applet from the browser cache and force
it to be reloaded.

> Note : mr Tompson and mr Woods i wrote down your remarks but I am
> trying to make one step at a time , Java is different from C/C++ that
> I have learned !!

Yes, but the trouble is you are trying to
'leap frog' or 'jump over' some parts of
Java that you need to understand, doing
this in an applet (right now) is a bad idea.

HTH

0 new messages