Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

serpe75

[java] Code of a basic server for multiplayer game programming

This topic is 5753 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

I''m a beginner in multiplayer game programming and I''m lookin for the code of a basic server (possibly written in Java) that will accept incoming connections from different clients and start a thread which will than copy the information into the client structure for its own use. Coul anyone help me?

Share this post


Link to post
Share on other sites
Advertisement
Basicly you are looking for something like this (if using TCP sockets):

    
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;

public class Server {
private int port; // The port number

private volatile boolean serverRunning = true; // Set to false when you want to stop accepting connections


/* Method that accepts connections and spawns new threads to handle them. */
public void handleConnection() {
ServerSocket serverSocket = new ServerSocket(portNumber);
while(serverRunning) {
try {
Socket s = serverSocket.accept();
Thread t = new Thread(new ConnectionHandler(s));
t.start();
} catch(IOException) {
// Handle exception
}
}
}
}

/* Class that handles new connections, implements the Runnable interface in order to allow it to be used to start new threads. */
class ConnectionHandler implements Runnable {
private Socket socket;
public ConnectionHandler(Socket s) {
socket = s;
}

public void run() {
/* Here you put the code that reads from the socket and copies the data to the server's internal structure. */

}
}


Note that I just typed this into the post so I don't know if it compiles or runs, but it should give you the general idea.

[edited by - HenryAPe on September 15, 2002 3:18:22 PM]

Share this post


Link to post
Share on other sites
Search the Java Tutorial (java.sun.com), for the Sockets example, there is a fine and simple example of doing a MultiTHreaded server

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!