Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Another problem.
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Donny




PostPosted: Mon Apr 18, 2011 12:57 pm   Post subject: Another problem.

Again i've googled to no avail trying to get this to work. I have an int that keeps changing (that's what i want it to do) but i need to get just 1 id from it, like grab the number before it changes, and keep that.. How do I do this? I don't know how to word it better maybe that's why google has failed me. Thanks.


Suppose I should tell you what i'm doing: I'm writing a game with Java sockets, and everytime a client connects, i use the clientid++ command to change the id, the first client connects, it registers as client 1, then another connects it's client 2, but then when i look at the output for client 1 it's not identifying as client 2 aswell... I want to just grab 1 id from the client because that's what i'm sending. Thanks, hopefully this didn't make my situation more confusing.
Sponsor
Sponsor
Sponsor
sponsor
DemonWasp




PostPosted: Mon Apr 18, 2011 2:48 pm   Post subject: RE:Another problem.

Your explanation is missing a lot of details that would be very helpful. How does client 1 know that it's client 1 (does it?)? How does the server know which client is which? Are you using TCP or UDP? Do you have any prior experience with network programming?

Alternately, you could post your source code. Don't forget to use [ syntax="Java" ] [ /syntax ] around your code.
Donny




PostPosted: Mon Apr 18, 2011 2:57 pm   Post subject: RE:Another problem.

I have a lot of classes, and it is TCP, the server tells the client which client id it is, but it's also telling all of the clients their numbers, but it's telling the number connected and not the actual number (i want both), and no i'm a beginner in java sockets..

CODE:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package testgame;

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

/**
 *
 * @author Donny
 */
public class Main {
            static int port = 7777;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception{

        ServerSocket ss = new ServerSocket(port); //start server on port
        System.out.println("Server started");
        Socket s = null; //creates a socket
        System.out.println("Waiting for connection...");
        newClient newc = new newClient();
        while (true){
        newc.client(ss.accept());
        }
       
       
    }

}


CODE:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package testgame;

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

/**
 *
 * @author Donny
 */
public class Communicate extends Char {
    static int initport = 7777;
    static int runport = 7778;
    public int initialclientid;
    public int clientid;
    public int portid;
    public void initial() throws Exception{
       
        Socket s = new Socket("localhost", initport);
        DataInputStream inFromServer = new DataInputStream(s.getInputStream());
        DataOutputStream outToServer = new DataOutputStream(s.getOutputStream());
        initialclientid = inFromServer.readInt();
        System.out.println("CLIENTID: " + initialclientid);
    }
    public void keepComs() throws Exception{
        Socket s = new Socket("localhost", runport);
        DataInputStream inFromServer = new DataInputStream(s.getInputStream());
        DataOutputStream outToServer = new DataOutputStream(s.getOutputStream());
        clientid = inFromServer.readInt();
        outToServer.writeInt(clientid);
        System.out.println("clientid: " + clientid);
    }
}

CODE:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package testgame;

import java.io.*;
import java.net.*;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Donny
 */
public class newClient extends Main {
    int clientson;
    public void client(Socket socket) throws Exception{
     Socket s = socket;
     clientson++;
     System.out.println("Connected");
        DataInputStream inFromClient = new DataInputStream(s.getInputStream());
        DataOutputStream outToClient = new DataOutputStream(s.getOutputStream());
        outToClient.writeInt(clientson);

        Timer t = new Timer();
        t.schedule(new TimerTask(){public void run(){
            keepClient k = new keepClient();
            final int j = clientson;
            int clientid = 0;
                    try {
                        k.keepClient(new ServerSocket(7778), j, clientid);
                    } catch (Exception ex) {
                        Logger.getLogger(newClient.class.getName()).log(Level.SEVERE, null, ex);
                    }

        }}, 10, 1000);
       
    }
}


CODE:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package testgame;

import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;



/**
 *
 * @author Donny
 */
public class Client extends Communicate{
    public void init(){
    setSize(300,300);
    Client c = new Client();
    Communicate coms = new Communicate();
        try {
            coms.initial();
            Timer t = new Timer();
            t.schedule(new TimerTask(){public void run(){
            Communicate coms = new Communicate();
                    try {
                        coms.keepComs();
                    } catch (Exception ex) {
                        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
                    }
            }}, 10, 1000);
           

        } catch (Exception ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

CODE:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package testgame;
import java.net.*;
import java.io.*;
import java.util.Random;
/**
 *
 * @author Donny
 */
public class keepClient extends newClient {
    int clientid;
        public void keepClient(ServerSocket ssocket, int clientson, int clientid) throws Exception{

            ServerSocket ss = ssocket;
            Socket s = ss.accept();
             DataInputStream inFromClient = new DataInputStream(s.getInputStream());
             DataOutputStream outToClient = new DataOutputStream(s.getOutputStream());
             outToClient.writeInt(clientid);
             clientid = inFromClient.readInt();
             ss.close();
        }
}

CODE:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package testgame;

import java.applet.Applet;

/**
 *
 * @author Donny
 */
public class Char extends Applet {

}
DemonWasp




PostPosted: Mon Apr 18, 2011 4:33 pm   Post subject: RE:Another problem.

I think that, rather than diving into that jungle, it might be best to start with the basics. You've made your life much harder by writing so much code -- I was having a hard time understanding what all your code is supposed to do. So, for the moment, ignore all that code. We'll make this as simple as possible.

You're going to have two applications. One will be Server, one will be Client. You will run them separately -- just start the Server application first, then the Client application. You can do this all from within NetBeans, which is what you seem to be using.

Server.java
Java:

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

public class Server {
        public static void main ( String[] args ) throws IOException {
                ServerSocket serverSocket = new ServerSocket ( 7777 );

                System.out.println ( "Server ready!" );

                // Loop forever, accepting connections...
                int clientNum = 0;
                while ( true ) {
                        // Wait for a connection...
                        Socket socket = serverSocket.accept();

                        // Set up IO streams
                        DataOutputStream out = new DataOutputStream ( socket.getOutputStream() );
                        DataInputStream in = new DataInputStream ( socket.getInputStream() );

                        // Send the ID to that client...
                        out.writeInt ( clientNum );

                        // Get an ID from that client...
                        int clientID = in.readInt();

                        // Now we expect that the client will have sent back the ID we gave it...
                        if ( clientID != clientNum ) {
                                System.out.println ( "Whoops: the client send back "+clientID+" but we expected"+clientNum );
                        } else {
                                System.out.println ( "Client gave correct ID #"+clientID );
                        }

                        socket.close();

                        // On to the next client!
                        ++clientNum;
                }
        }
}


Java:

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

public class Client {
        public static void main ( String[] args ) throws IOException {
                // Connect to the server...
                Socket socket = new Socket ( "localhost", 7777 );

                // Set up our IO streams...
                DataInputStream in = new DataInputStream ( socket.getInputStream() );
                DataOutputStream out = new DataOutputStream ( socket.getOutputStream() );

                // Get the ID from the server
                int clientID = in.readInt();

                System.out.println ( "Server gave us ID #"+clientID );

                // Return the ID to the server
                out.writeInt ( clientID );

                socket.close();

                System.out.println ( "Goodbye!" );
        }
}


Try those. You should get output like this from the server:
code:

Server ready!
Client gave correct ID #0
Client gave correct ID #1
Client gave correct ID #2
Client gave correct ID #3
Client gave correct ID #4


And this from running the client a few times:
code:

Server gave us ID #0
Goodbye!
Server gave us ID #1
Goodbye!
Server gave us ID #2
Goodbye!
Server gave us ID #3
Goodbye!
Server gave us ID #4
Goodbye!



Read and understand that code. Then, move on to modifying it to do what you want. Try to keep everything as simple as possible at every step of the way -- networked programming is tricky enough that you don't need extra complexity.
Donny




PostPosted: Mon Apr 18, 2011 4:40 pm   Post subject: RE:Another problem.

Thanks, I've kinda done that, but my code keeps sending back and forth from server - client (it's going to be updating the player position) so what happens when you run multiple clients? (my original problem) that keep updating? Mine did that before I added the timers and such.
DemonWasp




PostPosted: Mon Apr 18, 2011 7:42 pm   Post subject: RE:Another problem.

There are a couple of solutions. One is more complicated than the other, but the other is messier.


Complicated Solution:
Multithreading. Spawn multiple threads (at least one per connection, depending on your model) to gather and send data over the IO streams of each socket.

This is complicated because synchronization, multithreading, and concurrency are inherently more difficult than single-threaded programming. Multiple threads means a whole host of new concerns, problems, and complexity. Java provides some pretty nice features to make a programmer's life simpler, but it's still pretty hard work to get it right.

See the SUN Java tutorial on concurrency: http://download.oracle.com/javase/tutorial/essential/concurrency/ , but also frequently refer to Wikipedia and any online lectures you can find on the subject, because multithreaded programming is difficult, tricky, and easy to screw up, even for experienced programmers.

This is the solution most professional programmers will choose, for a variety of reasons.



Messy Solution:
Polling. You use a limited number of threads (probably one for the ServerSocket.accept() call, which blocks until a connection is made, plus one for the "main processing loop"). On each iteration of the main processing loop, look at the amount returned by the "available()" method on Socket to determine whether you want to stop and read from that socket, or whether you'd like to move on (without waiting for more data).

This is simpler because it's essentially single-threaded (and the bits where it isn't aren't super critical or difficult). However, it's also way messier because you have to have some idea of how many bytes need to be available before you can read a whole message at a time. Although you can use mark(), read() and reset() to look-ahead for a length or message-type field, it'll be a bit of work (and a lot of reading) to get it exactly right.

Example: You have two clients, A and B. Each sends you a message, with A's message being 20 bytes and B's being 36. When you get around to processing data on those InputStreams, A has 20 bytes available and B, by sheer coincidence, also has 20 bytes available.

You mark() A's stream, then read the message-header fields, which are message_type (2 bytes, unsigned short) and message_length (2 bytes, unsigned short). You know that since message_length <= available(), you can read the whole message, so you do. You move on to B.

You mark() B's stream, then read the message-header fields (exactly the same for all messages!). You know that since message_length == 36 > available(), you canNOT read the whole message. You use reset() to "back up" in the InputStream. You move on to either client C, or the next step in the main processing loop (handling received Messages?).
Donny




PostPosted: Mon Apr 18, 2011 8:08 pm   Post subject: RE:Another problem.

I think I'll leave an MMORPG until later in my career, I have another question however. I wish to create a Sprite class, when i call the paint method in the sprite class i have
CODE:

public void paint(Graphics g, int x, int y){
       g.drawOval(x,y,10,10);
}

how can I call that form my main class? I've tried to google but I don't know what search terms will give me results, for now, I've got nothing. I call in the main class
CODE:

Sprite s = new Sprite();
s.paint(null,10,10);

it give me null by default, I don't know what to change it to for it to work, any suggestions?


EDIT: I'm working in Applet's btw, dunno if that makes a difference.
DemonWasp




PostPosted: Mon Apr 18, 2011 8:40 pm   Post subject: RE:Another problem.

You'll need to get a Graphics object from one of the classes you use for your GUI within the Applet. I don't know a huge amount about this, but you've probably got a paint ( Graphics g ) method somewhere that will get called by the JVM (that is, you don't call it, it just gets called automatically).

That method is where you should call all your other paint(...) methods.
Sponsor
Sponsor
Sponsor
sponsor
Donny




PostPosted: Mon Apr 18, 2011 8:57 pm   Post subject: RE:Another problem.

You are so helpful Razz thank you very much.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 9 Posts ]
Jump to:   


Style:  
Search: