关闭

基于TCP/IP的手机聊天游戏(附带源码和解释)之服务器端类

1839人阅读 评论(3) 收藏 举报

服务器端也很简单,就是开一个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.");
    }

}

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:827074次
    • 积分:9617
    • 等级:
    • 排名:第1909名
    • 原创:120篇
    • 转载:35篇
    • 译文:3篇
    • 评论:1121条
    新浪微博
    最新评论