Sign in to follow this  

Java: 2 player Network game

This topic is 4679 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I have a basic game running in Java similar to SmashTV on the snes (top down shooter). I would like to enable 2 players to play the game on seperate computers using sockets so that both players can see each other on their screns. I have written some code that I think should work but it doesnt seem to be sending messages as I would like. from the main Game class 1 player starts a Server thread ... <CODE> import java.io.*; import java.net.*; import java.util.*; import java.text.*; public class Server extends Thread { Server() { } public void Run() { String line = "Start"; boolean serve = true; BufferedReader in ; PrintStream out ; try { ServerSocket server = new ServerSocket(80); // Open new socket on port 80. Socket client = server.accept(); // Wait for a client to connect. // Create a reader to take in messages. in = new BufferedReader(new InputStreamReader(c ient.getInputStream())); // Create an output stream to send messages back. out = new PrintStream(new BufferedOutputStream(client.getOutputStream())); while(true) { line = in.readLine(); System.out.println(line); // Print out result to test its working } } catch (IOException e) { System.out.println(e); } } public static void main(String[] args) { Server ser = new Server(); } } </CODE> ... The other player then starts a Client thread ... <CODE> import java.io.*; import java.net.*; import java.util.*; import java.text.*; import javax.swing.*; public class Client extends Thread { BufferedReader in ; PrintStream out ; public Client() { } public void Run() { Socket MyClient = null; try { MyClient = new Socket("localhost", 80); in = new BufferedReader(new InputStreamReader(MyClient.getInputStream())); // Create an output stream to send requests on. out = new PrintStream(new BufferedOutputStream(MyClient.getOutputStream())); } catch (IOException e) { System.out.println(e); } } public static void main(String[] args) { Client cli = new Client(); cli.sendMessage("Client started"); } public void sendMessage(String msg) { out.print(msg); System.out.println("Working"); } } </CODE> Surely when I call sendMessage on the client side the Server should recieve the message, however it does not. This is strange because the code works when I take it out of the game and run it alone as 2 classes. Any ideas why, am i doing this totally wrong ??? Cheers Chris

Share this post


Link to post
Share on other sites

Hi,

Have you checked to see what is actually being sent? May be stick in the following:


public void sendMessage(String msg)
{
JOptionPane.showMessageDialog(null, msg);
out.print(msg);
}


Just a suggestion as of now. I haven't really studied the code to much. I don't know too much about Java networking.

On another note, a good friend and I are creating a SmashTv clone ourselves using the allegro library and C langauge. Maybe you could PM me when finished? I would be interested in your finished product :)

Share this post


Link to post
Share on other sites
Quote:
Original post by chris_j_pook
At the moment I am just passing a string "Hello" to the sendMessage function. I think it must be something to do with the way it is running as a thread or being called constantly by the mainGame loop thats causing the problems.


Threading? I'd recommend putting it all in one thread/main loop for now. If it doesn't work, you've then narrowed your problem. I don't know how much code you've written, but you should be able to isolate the problem. One advantage of Java is that it's very easy to test modules of code. You're probaly going to have to get someone else to help you. I'm not to exceptional at networking (as of yet).

GCS584

[EDIT:] Multi-threading is normally more difficult to debug

Share this post


Link to post
Share on other sites
have you writen another code besides that or is it your first code of the game?
means- do you already have a ready game and all you need is the socket programing or you started from the socket programming and havent no code yet?
btw i can give you my connection code, it is a chat between 2 people with no graphics, prety much same like your code but mine works :) (lol).

Share this post


Link to post
Share on other sites
have you writen another code besides that or is it your first code of the game?
means- do you already have a ready game and all you need is the socket programing or you started from the socket programming and havent no code yet?
btw i can give you my connection code, it is a chat between 2 people with no graphics, prety much same like your code but mine works :) (lol).

Share this post


Link to post
Share on other sites
have you writen another code besides that or is it your first code of the game?
means- do you already have a ready game and all you need is the socket programing or you started from the socket programming and havent no code yet?
btw i can give you my connection code, it is a chat between 2 people with no graphics, prety much same like your code but mine works :) (lol).

Share this post


Link to post
Share on other sites
I think there are some problems with your threading code. First off, "public void Run()" should be "public void run()" with a lower case 'r'. Also, I don't see where you're calling the start() method. Maybe you just left that out of the example code you provided here?

There's a nice tutorial on threading in Java at: http://java.sun.com/docs/books/tutorial/essential/threads/simple.html.

I prefer to create threads by implementing the Runnable interface. You can read up on that here: http://java.sun.com/docs/books/tutorial/essential/threads/clock.html

Hope this helps.

Tony

Share this post


Link to post
Share on other sites
Hi,

I call the relevent start method from the main Game class when the player chooses to start a server or join one.

I have changed the Run() to run() and made it implement Runnable but still no joy...

What is strange is the way it works when I take this code and run it away from the game part as single classes rather than threads. Is there some sort of waiting or something I need to do ?

Chris

Share this post


Link to post
Share on other sites
Here are your two programs with all of the threading stuff removed and a few more changes. These work as expected for me.


import java.io.*;
import java.net.*;

public class Server {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket( 8080 );

// Wait for a client to connect.
Socket socket = server.accept();

System.out.println( "Client connected..." );

// Create a reader to take in messages.
BufferedReader in = new BufferedReader(
new InputStreamReader( socket.getInputStream() ) );

// wait for data to appear
while( !in.ready() ) {
// do nothing
}

String line = in.readLine();

// Print out result to test its working
System.out.println( line );

socket.close();
}
catch (IOException e) {
System.out.println( e );
}
}
}





import java.io.*;
import java.net.*;

public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket( "localhost", 8080 );

System.out.println( "Socket created..." );

// Create an output stream to send requests on.
PrintWriter out = new PrintWriter(
new BufferedOutputStream( socket.getOutputStream() ) );

out.print( "Hello World!" );
out.flush();

System.out.println( "Data sent." );

socket.close();
}
catch( IOException e ) {
System.out.println( e );
}
}
}




Basically, I added some code to the Server to wait for data to appear on the input stream, and I added out.flush() to the Client to make sure that the data gets sent.

Tony

Share this post


Link to post
Share on other sites
Ok I have put this code in to my game now...

At the start of the game either createServer() or createClient() is called, these contain the code you posted above.

This does work, in that when the Client socket is created it sends a message and the server game prints out Hello World...

However, if I then try to send more messages either using out.print("...") in Game class (I have PrintStream out as a global variable in the Game class) or by calling createClient() again the Server does not seem to receive the message.

I cant think why this would be ...

Any ideas ?

Chris

Share this post


Link to post
Share on other sites
Note that the server code I provided earlier closes the socket after printing one line of text and then exits. Here's a slightly more advanced server that should handle multiple lines of text on the same socket and will accept another connection after the first one is closed:


import java.io.*;
import java.net.*;

public class Server {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket( 8080 );

// this server will live forever
while ( true ) {
// Wait for a client to connect.
Socket socket = server.accept();

System.out.println( "Client connected..." );

// Create a reader to take in messages.
BufferedReader in = new BufferedReader(
new InputStreamReader( socket.getInputStream() ) );

// wait for data to appear
while( !in.ready() ) { /* do nothing */ }

// read multiple lines
while( true ) {
String line = in.readLine();
if ( line == null ) {
break;
}
System.out.println( line );
}

// close the socket
socket.close();
System.out.println( "Connection closed." );
}
}
catch( Exception e ) {
System.out.println( e );
}
}
}



Tony

Share this post


Link to post
Share on other sites
Ahhhh,

Thankyou... I should have realised the server was only taking one message and closing, I now have my game server and client communicating once per game loop.

Should be no problem to pass game variables between them now.

Thanks for your help

Chris

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Have you got a download link for a compiled version? A couple of us did an alpha version of a smashtv clone: http://grexengine.com/sections/games/survivor/ which we mean to finish off sometime (including 8-way or more multiplayer) but haven't got around to yet.

If anyone wants to work on this feel free to get in touch on ceo at grexengine.com (put "survivor" in the subject line and it'll get forwarded on to us).

Share this post


Link to post
Share on other sites

This topic is 4679 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this