Socket LAN game

Can't display the client window properly

  • (2 Pages)
  • +
  • 1
  • 2

27 Replies - 4522 Views - Last Post: 15 June 2010 - 10:31 AM Rate Topic: -----

#1 gumstic  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 1
  • View blog
  • Posts: 44
  • Joined: 28-October 06

Socket LAN game

Posted 02 June 2010 - 01:12 PM

I'm trying to use sockets to just be able to view a 'server session' from a second 'client session' game of solitaire.

Since the game is split into classes, I'm using the main class to fit in the server/client socket initialisation, but having trouble getting to show the changes made from the 'server session'.

public class solitaireMain extends JFrame {

	public static void main(String[] args) throws IOException, Exception {

		JFrame f = new JFrame("Solitaire"); // Title
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		solitaireGUI solitaireWindow = new solitaireGUI();
		f.setContentPane(solitairewindow.createGUI(f));

		f.setSize(970, 700);
		f.setResizable(false);
		f.setVisible(true);
		f.pack();
		
		// Setup the server and client sockets
		char ch;
     	if (args.length == 0)
     		ch = 's';
     	else 
     		ch = 'c';
     	
		Socket server;
		ObjectOutputStream outputStream;
		ObjectInputStream inputStream;

		// setup the server (host)
		 switch (ch) {
         case 's':
        	 server = (new ServerSocket(7777)).accept();
        	 System.out.println("Listening on port 7777...");
        	 outputStream = new ObjectOutputStream(server.getOutputStream());
        	 outputStream.writeObject(f);
        	 break;
         case 'c':
         // else setup the client
         default:
            server = new Socket(args[0],7777);
            System.out.println("Connected to Server using port 7777.");
		 }
		 
		 // listen for I/O
		 while(true) {
			 inputStream = new ObjectInputStream(server.getInputStream());
             f = (JFrame)(inputStream.readObject());
             f.paint(f.getGraphics());
             outputStream = new ObjectOutputStream(server.getOutputStream());
             outputStream.writeObject(f);
          }
	}
}



Running the above code from 2 different cmd-line windows ("java solitaireMain", "java solitaireMain localhost", I get the server listening and the client connected, but also get an exception that one of the arrays is not a valid serializable object and breaks in another class.

Am I doing the socket connections correctly?

:blink:

Is This A Good Question/Topic? 0
  • +

Replies To: Socket LAN game

#2 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2640
  • View blog
  • Posts: 11,155
  • Joined: 20-September 08

Re: Socket LAN game

Posted 02 June 2010 - 03:42 PM

I think you need to look at your paradigm: you're attempting to serialize a whole frame. Its entire object tree would need to be serializable. That's quite heavy. You should look at only sending the smallest change delta objects only, and then reflecting those changes in the receiving gui
Was This Post Helpful? 0
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Socket LAN game

Posted 02 June 2010 - 04:48 PM

And when you will receive a whole serialized JFrame on the client side how will you deserialize it an extract the components that you will want to display in the client JFrame ? Or you ar eplanning to shutdown the Frame and display the new one ?

Better just to send the changes as a deck of Cards, their position and which side is showed
Was This Post Helpful? 0
  • +
  • -

#4 gumstic  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 1
  • View blog
  • Posts: 44
  • Joined: 28-October 06

Re: Socket LAN game

Posted 03 June 2010 - 12:42 PM

Ok. I get the picture, but how would I go about sending specific content rather than a frame. Would I send only the mouse events or just a dragging card ?
Was This Post Helpful? 0
  • +
  • -

#5 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2640
  • View blog
  • Posts: 11,155
  • Joined: 20-September 08

Re: Socket LAN game

Posted 03 June 2010 - 12:52 PM

You'd send the minimum info necessary to reconstruct the changes at the other end
Was This Post Helpful? 0
  • +
  • -

#6 gumstic  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 1
  • View blog
  • Posts: 44
  • Joined: 28-October 06

Re: Socket LAN game

Posted 05 June 2010 - 02:36 AM

For the socket connection I have changed from Main[] to the Layout class
as this is where all the actions take place and graphics are being rendered.
Have set the following menu actions to initialise and make the connection,
but hangs at line: 'socket = hostServer.accept();' in the else if
menuAction == 7 -Cant do much without that :angry2:

Menu:
-Set Server
private void setAsHost() {
		if (connectionStatus != DISCONNECTED) {
			changeStatusTS(NULL, true);
		} else {
			isHost = true;

			// Cannot supply host IP if host option is chosen
			if (isHost) {
				System.out.println("Set as host.");
				hostIP = "localhost";
			} else {
				System.out.println("Set as client.");
			}
		}
	}


-Connect host/client
...
} else if (menuAction == 7) {
			System.out.println("clicked menu 7 (client)...");

			changeStatusTS(BEGIN_CONNECT, true);
			String s = "";
//			while (true) {
//				try { // Poll every ~10 ms
//					Thread.sleep(10);
//				} catch (InterruptedException e) {
//				}

				switch (connectionStatus) {
				case BEGIN_CONNECT:
					try {
						// Try to set up a server if host
						if (isHost) {
							hostServer = new ServerSocket(port);
							socket = hostServer.accept();
						}

						// If guest, try to connect to the server
						else {
							socket = new Socket(hostIP, port);
						}

						in = new BufferedReader(new InputStreamReader(socket
								.getInputStream()));
						out = new PrintWriter(socket.getOutputStream(), true);
						changeStatusTS(CONNECTED, true);
					}
					// If error, clean up and output an error message
					catch (IOException e) {
						cleanUp();
						changeStatusTS(DISCONNECTED, false);
					}
					break;

				case CONNECTED:
					try {
						// Send data
						if (toSend.length() != 0) {
							out.print(toSend);
							out.flush();
							toSend.setLength(0);
							changeStatusTS(NULL, true);
						}

						// Receive data
						if (in.ready()) {
							s = in.readLine();
							if ((s != null) && (s.length() != 0)) {
								// Check if it is the end of a trasmission
								if (s.equals(END_CHAT_SESSION)) {
									changeStatusTS(DISCONNECTING, true);
								}

								// Otherwise, receive what text
								else {
									appendToChatBox("INCOMING: " + s + "\n");
									changeStatusTS(NULL, true);
								}
							}
						}
					} catch (IOException e) {
						cleanUp();
						changeStatusTS(DISCONNECTED, false);
					}
					break;

				case DISCONNECTING:
					// Tell other chatter to disconnect as well
					out.print(END_CHAT_SESSION);
					out.flush();

					// Clean up (close all streams/sockets)
					cleanUp();
					changeStatusTS(DISCONNECTED, true);
					break;

				default:
					break; // do nothing
				}
//			}

		} else if (menuAction == 8) {
			System.out.println("clicked menu 8 (exit)...");
			System.exit(DISCONNECTING);
		}
...


:blink:

This post has been edited by gumstic: 05 June 2010 - 03:27 AM

Was This Post Helpful? 0
  • +
  • -

#7 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2640
  • View blog
  • Posts: 11,155
  • Joined: 20-September 08

Re: Socket LAN game

Posted 05 June 2010 - 04:10 AM

Quote

but hangs at line: 'socket = hostServer.accept();'


Well, that call is meant to block
Was This Post Helpful? 0
  • +
  • -

#8 gumstic  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 1
  • View blog
  • Posts: 44
  • Joined: 28-October 06

Re: Socket LAN game

Posted 05 June 2010 - 05:07 AM

Its not suppose to 'hang' though, right? It should let the game continue to
work whether a connection will come in or not.

There must be something else I'm missing.
Was This Post Helpful? 0
  • +
  • -

#9 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2640
  • View blog
  • Posts: 11,155
  • Joined: 20-September 08

Re: Socket LAN game

Posted 05 June 2010 - 05:09 AM

Well the word 'hang' implies that you're experiencing that it stops other things from happening. It certainly will do in the thread in which it runs, so if that's your app's main thread, you'll have problems. You need to listen for the socket connection in a separate thread
Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Socket LAN game

Posted 05 June 2010 - 12:07 PM

View Postgumstic, on 05 June 2010 - 06:07 AM, said:

Its not suppose to 'hang' though, right? It should let the game continue to
work whether a connection will come in or not.

There must be something else I'm missing.

The server if waiting for a client to connect
It will stay waiting on that line until a client connects

If you want multiple clients to be able to connect and receive game update messages you will have to follow g00se suggestions and have a separate thread that listen for client connections, store them in an List and scan that list to update all connected clients when the player moves a card.

The first time a client connects you will have to send it all cards position.

It is a fun program.
Was This Post Helpful? 0
  • +
  • -

#11 gumstic  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 1
  • View blog
  • Posts: 44
  • Joined: 28-October 06

Re: Socket LAN game

Posted 05 June 2010 - 01:12 PM

Which is the simplest way I could send string messages from the host to a client
connected (and see them on the client)?

I want to test if the connection is working (with the code I have) and then
move on to more complicated stuff...

Based on this code:
public class solitaireMain extends JFrame {

        public static void main(String[] args) throws IOException, Exception {

                JFrame f = new JFrame("Solitaire"); // Title
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                solitaireGUI solitaireWindow = new solitaireGUI();
                f.setContentPane(solitairewindow.createGUI(f));

                f.setSize(970, 700);
                f.setResizable(false);
                f.setVisible(true);
                f.pack();
                
                // Setup the server and client sockets
                char ch;
        if (args.length == 0)
                ch = 's';
        else 
                ch = 'c';
        
                Socket server;
                ObjectOutputStream outputStream;
                ObjectInputStream inputStream;

                // setup the server (host)
                 switch (ch) {
         case 's':
                 server = (new ServerSocket(7777)).accept();
                 System.out.println("Listening on port 7777...");
                 outputStream = new ObjectOutputStream(server.getOutputStream());
                 outputStream.writeObject(f);
                 break;
         case 'c':
         // else setup the client
         default:
            server = new Socket(args[0],7777);
            System.out.println("Connected to Server using port 7777.");
                 }
                 
                 // listen for I/O
                 while(true) {
                         inputStream = new ObjectInputStream(server.getInputStream());
             f = (JFrame)(inputStream.readObject());
             f.paint(f.getGraphics());
             outputStream = new ObjectOutputStream(server.getOutputStream());
             outputStream.writeObject(f);
          }
        }
}


Was This Post Helpful? 0
  • +
  • -

#12 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Socket LAN game

Posted 05 June 2010 - 01:23 PM

As String are serializable it is quite easy

String str;
objectOutputStream.writeObject(str);

String clientSide = (String) objectInputString.readObject();
Was This Post Helpful? 0
  • +
  • -

#13 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2640
  • View blog
  • Posts: 11,155
  • Joined: 20-September 08

Re: Socket LAN game

Posted 05 June 2010 - 02:42 PM

Don't forget that the threading issue applies to both ends of the socket.

You will find that it simplifies implementation to use the socket and then close it
Was This Post Helpful? 0
  • +
  • -

#14 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Socket LAN game

Posted 05 June 2010 - 02:46 PM

View Postg00se, on 05 June 2010 - 03:42 PM, said:

Don't forget that the threading issue applies to both ends of the socket.

You will find that it simplifies implementation to use the socket and then close it

Hein ! Where and when ?
Use UDP in that case
Was This Post Helpful? 0
  • +
  • -

#15 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2640
  • View blog
  • Posts: 11,155
  • Joined: 20-September 08

Re: Socket LAN game

Posted 05 June 2010 - 02:51 PM

Quote

Where and when ?


What i'm getting at is that people often think that for continuous tcp/ip comms, you need continuously open sockets. This isn't the case, and keeping them open can cause various gotchas
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2