Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (515)
Games in Android Showcase (122)
games submitted by our members
Games in WIP (577)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Starting out: Client / Server, Multithreaded, and Mouse.x and .y  (Read 2798 times)
0 Members and 1 Guest are viewing this topic.
Offline Water_SS

Innocent Bystander





« Posted 2011-04-18 17:43:06 »

I am trying to make a game as such:
A single server with multiple java and/or java clients... oh hell- I'm trying to create a grid-based mmo card game where multiple java applets or clients connect to a single server.

The first step I want to take in learning about clients and servers is to have a simple, two-client and single-server setup where player one and player two can see the other's x and y mouse coordinates as target images on each client's screen. I'm thinking that both clients connect to the server, the server giving each player a different colored target. Perhaps it can support more than two people but I just want it to be simple so I can learn from it.

The next step is to create the game. I don't know much about servers, clients, packets, ect., but as an educated guess:
1) the Server (physical) holds each player's total cards, current deck, saved decks, profile information, ect.
2) the Client connects to the server and is fully dynamic so that it saves Nothing on the client's machine
3) the Client sends requests information depending on the current page of the client: Intro Page, Lobby and Chat, and Game. (perhaps more)

I've heard that UDP is better for action MMO's like Wow and Rag online, but TCP/IP requests only one packet at a time and doesn't move forward until the packet is sent. So I'm sure that I'd go with TCP/IP.

As far as I've seen, studied (Copy-Paste-Run-Study Code), I've been given this group of example codes for The Multithreaded Server and Multithreaded Client:

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;

public class Server_Threaded extends Frame implements ActionListener, WindowListener {

//*****  Mulit-threaded server, accepts multiple messages
//       expected to be run on hawk-cs.cs.unc.edu:8901


protected String DEFAULT_HOST = "hawk-cs.cs.unc.edu";
protected int DEFAULT_PORT = 8901;
String host;
int port;

ListenServer listen;

TextField hostDisplay, portDisplay;
TextArea logDisplay, msgDisplay;
Panel topPanel;
Panel middlePanel;
Panel buttonPanel;
Button listenButton, quitButton;


// **************  Server_Threaded

    public Server_Threaded ()  {

        super ( "Server_Threaded " );
        buildUI ();

    }  // end constructor


// **************  main

    public static void main ( String [ ] args )  {

        Server_Threaded server = new Server_Threaded ();

    }  // end main


//***********  Interface Methods   ***********


//****  ActionListener methods

  public void actionPerformed ( ActionEvent e )  {

    Object s = e.getSource();

    // *** process Button actions

    if ( s instanceof Button )  {

        if ( s == listenButton )  {
            listen = new ListenServer ( this );
            listen.start ();

        }  // end listenButton

        if ( s == quitButton )  {
            hide ();
            dispose ();
            }  // end quitButton

    }  // end process Button actions

  }  // end actionPerformed


//****  WindowListener methods

  public void windowActivated ( WindowEvent e )  {
  }

  public void windowDeactivated ( WindowEvent e )  {
  }

  public void windowOpened ( WindowEvent e )  {
  }

   public void windowClosed ( WindowEvent e )  {
  }

  public void windowClosing ( WindowEvent e )  {
    hide ();
    dispose ();
  }

  public void windowIconified ( WindowEvent e )  {
  }

  public void windowDeiconified ( WindowEvent e )  {
  }


//***********  Utility Methods   ***********

// **************  buildUI

  private void buildUI ()  {

    try {
        InetAddress here = InetAddress.getLocalHost ();
        host = here.getHostName ();
    }
    catch (UnknownHostException e) { ;}

    hostDisplay = new TextField ( host, 30 );
    portDisplay = new TextField ( Integer.toString ( DEFAULT_PORT ), 4 );
    topPanel = new Panel ();
    topPanel.setLayout ( new GridLayout ( 2, 1 ) );
    topPanel.add ( hostDisplay );
    topPanel.add ( portDisplay );

    logDisplay = new TextArea ( 40, 10 );
    msgDisplay = new TextArea ( 40, 10 );
    middlePanel = new Panel ();
    middlePanel.setLayout ( new GridLayout ( 2, 1 ) );
    middlePanel.add ( logDisplay );
    middlePanel.add ( msgDisplay );

    listenButton = new Button ( "Listen" );
    quitButton = new Button ( "Quit" );
    listenButton.addActionListener ( this );
    quitButton.addActionListener ( this );
    buttonPanel = new Panel ( );
    buttonPanel.add ( listenButton );
    buttonPanel.add ( quitButton );

    add ( "North", topPanel );
    add ( "Center", middlePanel );
    add ( "South", buttonPanel );

    resize ( 400, 450 );
    show ();

    }  // end buildUI


}  // end Server_Threaded
// ********************  ListenServer  ***********
class ListenServer extends Thread  {

Server_Threaded source;
ServerSocket listenSocket;
int port;
Socket connection;
HandleServer handle;
boolean again = true;


// **************  ListenServer constructor

    ListenServer ( Server_Threaded s)  {

        super ();

        source = (Server_Threaded ) s;

    }  // end constructor


// **************  run

    public void run  ()  {

        if ( ! ( source.portDisplay.getText () ).equals ( "" ) ) port = Integer.parseInt ( source.portDisplay.getText () );
        else port = source.DEFAULT_PORT;

        try  {

            listenSocket = new ServerSocket ( port );
            source.logDisplay.setText ( "Server started:\n  listening on port " + port + "\n\n" );

            while ( true )  {

                Socket connection = listenSocket.accept();
                HandleServer handleServer = new HandleServer ( connection, source );
                handleServer.start ();

            }  // end while

    }  catch ( IOException e )  {
        e.printStackTrace ();
        source.logDisplay.setText ( "Error is opening ServerSocket\n" );
        System.exit ( 1 );
    }  // end catch


}  // end run


}  // end ListenServer


/******************************** HandleServer  ***********/

class HandleServer extends Thread  {

Server_Threaded source;
Socket connection;

InputStream inStream;
DataInputStream inDataStream;
OutputStream outStream;
DataOutputStream outDataStream;

String message;


// **************  HandleServer constructor

    HandleServer ( Socket socket, Server_Threaded s)  {

        super ();
        connection =  socket;
        source =  s;

    }  // end constructor


// **************  run

    public void run  ()  {

        String stringIn, stringOut;
        boolean again = true;

        InetAddress inet = connection.getInetAddress ();
        String origin = inet.getHostName ();
        int originport = connection.getPort ();

        source.logDisplay.appendText ( "Adding Client: \n  "+origin+":"+originport+"\n\n" );


        try  {

            outStream = connection.getOutputStream ();
            outDataStream = new DataOutputStream ( outStream );
            inStream = connection.getInputStream ();
            inDataStream = new DataInputStream ( inStream );

            while ( true )  {

                message = inDataStream.readUTF ();
                source.logDisplay.appendText ( "  Message, below, received\n" );
                source.msgDisplay.setForeground ( Color.red );
                source.msgDisplay.setText ( message );

                outDataStream.writeUTF ( message );
                source.logDisplay.appendText ( "  Message returned to client \n\n" );

            }  // end while

        }  // end try

        catch ( EOFException except ) {
            source.logDisplay.appendText ( "  Connection closed by Client\n\n" );
            try  {
                connection.close ();
                return;
            }
            catch ( IOException e )  {
                e.printStackTrace ();
                return;
            }  // end IOException

         }  // end catch EOFException
         catch ( IOException e )  {
            source.logDisplay.appendText ( "  Connection closed abormally\n" );
            e.printStackTrace ();
            return;
         }  // end catch IOException


    }  // end run


}  // end HandleServer


-AND THE CLIENT-


import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;

public class Client_Threaded extends Frame implements ActionListener, WindowListener {

//*****  Mulit-threaded client, sends and receives multiple messages
//       expected to connect to server on hawk-cs.cs.unc.edu:8901


protected String DEFAULT_HOST = "hawk-cs.cs.unc.edu";
protected int DEFAULT_PORT = 8901;
String host;
int port;

ConnectServer connection;

TextField hostDisplay, portDisplay;
TextArea logDisplay, msgDisplay;
Panel topPanel;
Panel middlePanel;
Panel buttonPanel;
Button connectButton, sendButton, cancelButton, quitButton;


// **************  Client_Threaded

    public Client_Threaded ()  {

        super ( "Client_Threaded " );
        buildUI ();

    }  // end constructor


// **************  main

    public static void main ( String [ ] args )  {

        Client_Threaded client = new Client_Threaded ();

    }  // end main


//***********  Interface Methods   ***********


//****  ActionListener methods

  public void actionPerformed ( ActionEvent e )  {

    Object s = e.getSource();

    // *** process Button actions

    if ( s instanceof Button )  {

        if ( s == connectButton )  {
            connection = new ConnectServer ( this );
            connection.start ();
        }  // end connectButton

        if ( s == sendButton )  {
            connection.sendReceive ();
        }  // end sendButton

        if ( s == cancelButton )  {
            msgDisplay.setText ( "" );
        }  // end cancelButton

        if ( s == quitButton )  {
            logDisplay.appendText ( "Closing connection and quitting\n" );
            connection.closeConnection ();
            try {Thread.sleep ( 2000 );} catch ( InterruptedException except) {;}

            hide ();
            dispose ();
            System.exit ( 0 );

            }  // end quitButton

    }  // end process Button actions

  }  // end actionPerformed


//****  WindowListener methods

  public void windowActivated ( WindowEvent e )  {
  }

  public void windowDeactivated ( WindowEvent e )  {
  }

  public void windowOpened ( WindowEvent e )  {
  }

   public void windowClosed ( WindowEvent e )  {
  }

  public void windowClosing ( WindowEvent e )  {
    hide ();
    dispose ();
    System.exit(0);
  }

  public void windowIconified ( WindowEvent e )  {
  }

  public void windowDeiconified ( WindowEvent e )  {
  }


//***********  Utility Methods   ***********


// **************  buildUI

  private void buildUI ()  {

    try {
        InetAddress here = InetAddress.getLocalHost ();
        host = here.getHostName ();
    }
    catch (UnknownHostException e) { ;}

    hostDisplay = new TextField ( host, 30 );
    portDisplay = new TextField ( Integer.toString ( DEFAULT_PORT ), 4 );
    topPanel = new Panel ();
    topPanel.setLayout ( new GridLayout ( 2, 1 ) );
    topPanel.add ( hostDisplay );
    topPanel.add ( portDisplay );

    logDisplay = new TextArea ( 40, 10 );
    msgDisplay = new TextArea ( 40, 10 );
    msgDisplay.setText ("Default message.");
    middlePanel = new Panel ();
    middlePanel.setLayout ( new GridLayout ( 2, 1 ) );
    middlePanel.add ( logDisplay );
    middlePanel.add ( msgDisplay );

    connectButton = new Button ( "Connect" );
    sendButton = new Button ( "Send" );
    cancelButton = new Button ( "Cancel" );
    quitButton = new Button ( "Quit" );
    connectButton.addActionListener ( this );
    sendButton.addActionListener ( this );
    cancelButton.addActionListener ( this );
    quitButton.addActionListener ( this );
    buttonPanel = new Panel ( );
    buttonPanel.add ( connectButton );
    buttonPanel.add ( sendButton );
    buttonPanel.add ( cancelButton );
    buttonPanel.add ( quitButton );

    add ( "North", topPanel );
    add ( "Center", middlePanel );
    add ( "South", buttonPanel );

    resize ( 400, 450 );
    show ();

    }  // end buildUI


}  // end Server_Threaded
 

// ************************  ConnectServer Class ************************
 

class ConnectServer extends Thread  {

Client_Threaded source;

String host;
int port;
Socket connection;

InputStream inStream;
DataInputStream inDataStream;
OutputStream outStream;
DataOutputStream outDataStream;

String message;

public static final String DEFAULT_HOST = "hawk-cs.cs.unc.edu";
public static final int DEFAULT_PORT = 8901;


// **************  ConnectServer

    ConnectServer ( Client_Threaded c)  {

        super ();

        source = (Client_Threaded ) c;

        connectServer ();

    }  // end constructor


// **************  run

    public void run  ()  {

    }  // end run


// **************  connectServer

  public void connectServer (  )  {

    host = source.hostDisplay.getText ();
    if ( host.equals ("" ) ) host = source.DEFAULT_HOST;
    if ( ! ( source.portDisplay.getText () ).equals ( "" ) ) port = Integer.parseInt ( source.portDisplay.getText () );
    else port = source.DEFAULT_PORT;

    try  {
      connection = new Socket ( host, port );

      outStream = connection.getOutputStream ();
      outDataStream = new DataOutputStream ( outStream );
      inStream = connection.getInputStream ();
      inDataStream = new DataInputStream ( inStream );

      source.logDisplay.setText ( "Socket created: \n  connecting to server "+host+":"+port+"\n\n" );

    }  // end try

    catch ( IOException except)  {
      source.logDisplay.setText ( "Error connecting to server\n" );
      except.printStackTrace ();
      System.exit ( 1 );
    }  // end catch

  }  // end connectServer


// **************  sendReceive

  public void sendReceive ()  {

    try {

        message = source.msgDisplay.getText ();
        outDataStream.writeUTF ( message );
        source.logDisplay.appendText ( "Message, below, sent to Server\n" );

        source.msgDisplay.setText ( "" );
        source.msgDisplay.setForeground ( Color.red );

        message = inDataStream.readUTF ();
        source.msgDisplay.appendText ( message );
        source.logDisplay.appendText ( "  Message returned from server\n\n" );

    }  // end try for input

    catch ( EOFException except ) {
        source.logDisplay.appendText ( "EOF received\n" );
        closeConnection ();
    }  // end catch IOException
    catch ( IOException e )  {
        source.logDisplay.appendText ( "IOException\n" );
        e.printStackTrace ();
        return;
    }  // end catch IOException

  }  // end sendReceive


// **************  closeConnection

  public void closeConnection () {

    try {
      connection.close ();
     }  catch ( IOException except )  {
        source.logDisplay.appendText ( "  Error clossing conncetion\n" );
       except.printStackTrace ();
     }

  }  // end closeConnection


}  // end ConnectServer


So will i be using a client-server group like this or ... where can I learn to do what I've set out to do?
Offline Nate

JGO Kernel


Medals: 153
Projects: 4
Exp: 14 years


Esoteric Software


« Reply #1 - Posted 2011-04-18 20:08:23 »

TL;DR, use code blocks. Smiley

Offline ra4king

JGO Kernel


Medals: 353
Projects: 3
Exp: 5 years


I'm the King!


« Reply #2 - Posted 2011-04-19 03:39:29 »

Please use Swing not AWT for building GUI's. Swing is more advanced, dynamic, and recent than AWT.
But same as Nate, TL;DR.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Nate

JGO Kernel


Medals: 153
Projects: 4
Exp: 14 years


Esoteric Software


« Reply #3 - Posted 2011-04-19 04:35:37 »

WTG ra4king, making me feel bad.  Clueless

Nothing wrong with AWT. Swing is built on top of it so it is certainly supported. I do usually build GUIs in Swing and then drop to AWT for stuff like FileChooser.

Anyway, I read your post minus most of the code. You have generally the right idea. You can use sockets as in the code you posted. There are also libs available to handle some things for you. You might check out KryoNet in my sig. Don't worry, writing a networked game is plenty complicated enough that using a lib is only a minor shortcut. Smiley

Offline ra4king

JGO Kernel


Medals: 353
Projects: 3
Exp: 5 years


I'm the King!


« Reply #4 - Posted 2011-04-19 04:39:30 »

I just can't stand the look of AWT, like Windows 95-ish gray blocks Shocked

Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

TehJavaDev (30 views)
2014-10-27 03:28:38

TehJavaDev (26 views)
2014-10-27 03:27:51

DarkCart (39 views)
2014-10-26 19:37:11

Luminem (21 views)
2014-10-26 10:17:50

Luminem (25 views)
2014-10-26 10:14:04

theagentd (31 views)
2014-10-25 15:46:29

Longarmx (61 views)
2014-10-17 03:59:02

Norakomi (57 views)
2014-10-16 15:22:06

Norakomi (46 views)
2014-10-16 15:20:20

lcass (43 views)
2014-10-15 16:18:58
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!