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

Started by
2 comments, last by serpe75 21 years, 7 months ago
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?
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 numberprivate 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]
google for the "black art of java game programming" there was a chat server and client in there if I remember right.
Search the Java Tutorial (java.sun.com), for the Sockets example, there is a fine and simple example of doing a MultiTHreaded server
Ciro Durán :: My site :: gamedev.net :: AGS Forums

This topic is closed to new replies.

Advertisement