基於TCP/IP的手機聊天遊戲(附帶原始碼和解釋)之伺服器端類

gudesheng發表於2008-01-03

伺服器端也很簡單,就是開一個ServerSocket監聽Client端的連線,如果有連線,就把此連線加入到一個List中。之所以這樣處理,是為了管理使用者連線,比如將來你可能需要增加給特定的使用者傳送私人訊息的功能,那麼就可以從這個使用者列表中尋找特定的使用者進行傳送。

連線建立以後利用一個單獨的執行緒來進行通訊。

MultiPlayerServer類:

import java.io.IOException;
import java.net.ServerSocket;
import java.util.List;
import java.util.Vector;

public class MultiPlayerServer implements Server,Runnable{
    private List list;

    public MultiPlayerServer() {
        list = new Vector();
        Thread t2 = new Thread(this);
        t2.start();
    }
   
    public void distributeUpdate(int type,int player_id,String content) {
        ServerConnection conn;
        Message msg = new Message(type,player_id,content);
        for (int i = 0; i < list.size(); i++) {
            conn = (ServerConnection) list.get(i);
            conn.sendMessage(msg);
        }
    }

   

    public synchronized void removeConnection(ServerConnection conn) {
        list.remove(conn);
        System.out.println("removed connection for player " + conn.getPlayerID());
        System.out.println("connection list size is now " + list.size());
    }

  

    public void run() {
        ServerSocket socket;

        try {
            socket = new ServerSocket(PORT);
            System.out.println("multiplayer server listening @ " + PORT);

            for (; ; ) {
                    synchronized (this) {
                        list.add(new ServerConnection(socket.accept(),this));
                    }
                }
        } catch (IOException ioe) {
            System.out.println("*** MultiPlayerServer.run(): " + ioe);
        }
    }

}

ServerConnection類:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.*;

public class ServerConnection implements Runnable {
    private MultiPlayerServer server;
    private Socket socket;
    private DataInputStream in;
    private DataOutputStream out;
    private int player_id;
    private Message err;
    private boolean done;
   
    public static Hashtable userList = new Hashtable();
    public static int player_count;

    /**
     * Create a new instance for use with game engine 'engine',
     * socket 'socket', and server 'server'.
     */
    public ServerConnection(Socket socket,MultiPlayerServer server) {
        this.server = server;
        this.socket = socket;
        done = false;
        Thread thread = new Thread(this);
        thread.start();
    }

    private synchronized void handleSignup(String str) {
        player_id = player_count++;
        if (player_id < 0) {
            System.out.println("ServerConnection.handleSignup(): engine refused player sign-up");
            return;
        }
        userList.put(new Integer(player_id),str);
        System.out.println("signed up player " + player_id);
        Message msg = new Message(Message.SIGNUP_ACK,player_id,"-1");

        try {
            msg.archive(out);
        } catch (IOException e) {
            System.out.println("***: could not send msg " + err);
        }
    }

    private void handleClientStatus(Message msg) {
        server.distributeUpdate(Message.SERVER_STATUS,player_id,userList.get(new Integer(player_id))+" 說 :"+msg.getStr());
    }

    public int getPlayerID() {
        return player_id;
    } 
 

    /**
     * Send a message to the client connected to this instance
     */
    public synchronized void sendMessage(Message msg) {
        try {
            msg.archive(out);
        } catch (IOException e) {
            System.out.println("***: could not send msg " + msg);
        }
    }

    /**
     * main loop
     */
    public void run() {
        Message msg;

        try {
            in = new DataInputStream(socket.getInputStream());
            out = new DataOutputStream(socket.getOutputStream());

            while (!done) {
                msg = Message.createFromStream(in);
                switch (msg.getType()) {
                case Message.SIGNUP:
                 System.out.println("Server is handling : SIGNUP");
                    handleSignup(msg.getStr());
                    System.out.println("Server After : SIGNUP");
                    break;
                case Message.CLIENT_STATUS:
                 System.out.println("Server receive : CIENT_STATUS");
                    handleClientStatus(msg);
                    break;
                case Message.SIGNOFF:
                    break;
                default:
                    break;
                }
            }

            in.close();
            out.close();
            socket.close();
        } catch (Exception ioe) {
            System.out.println("*** ServerConnection.run(): " + ioe);
            server.removeConnection(this);
        }
        server.removeConnection(this);
        System.out.println("player " + player_id + " disconnected.");
    }

}

 



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=775426


相關文章