SmartFoxServer服务器端用户登录验证

说明:本示例演示的是一个 SmartFoxServer 服务器端用户登录验证。 
开发环境:Unity3d 2.6,SmartFoxServer 1.6.6,MyEclipse 
一,首先先写一个服务器端扩展的 Java 类。如下所示 
package com.song.unity3d.login; 
import java.nio.channels.SocketChannel; import java.util.LinkedList; 
import it.gotoandplay.smartfoxserver.data.User; import it.gotoandplay.smartfoxserver.data.Zone; import it.gotoandplay.smartfoxserver.events.InternalEventObject; import it.gotoandplay.smartfoxserver.exceptions.LoginException; import it.gotoandplay.smartfoxserver.extensions.AbstractExtension; import it.gotoandplay.smartfoxserver.extensions.ExtensionHelper; import it.gotoandplay.smartfoxserver.lib.ActionscriptObject; 
/**  *  * @author songvery  * @version 2011-03-09-01  *  */ public class MyExtension extends AbstractExtension { 
 private ExtensionHelper helper;    private Zone currentZone;    //private DbManager db;    LinkedList<SocketChannel> recipients;        public void init(){   recipients=new LinkedList<SocketChannel>();   helper = ExtensionHelper.instance();   this.currentZone = helper.getZone(this.getOwnerZone());  }    public void destory(){    
 
 
 }    public void handleRequest(String cmd, ActionscriptObject ao, User user,    int fromRoom) {   // TODO Auto-generated method stub     } 
 public void handleRequest(String cmd, String[] params, User user, int fromRoom) {   // TODO Auto-generated method stub     } 
 public void handleInternalEvent(InternalEventObject ie) {      if(ie.getEventName().equals("loginRequest")){    ActionscriptObject response=new ActionscriptObject();        User loginUser=null;        //用户名    String name=ie.getParam("nick");        //密码    String pwd=ie.getParam("pass");        //ScocketChannel        SocketChannel chan=(SocketChannel)ie.getObject("chan");        //String serverRandom=helper.getSecretKey(chan);        //省去查询数据库验证的操作,自己写吧!    if(name.equals(pwd)){     try{      loginUser=helper.canLogin(name, pwd, chan, this.currentZone.getName());            response.put("cmd", "loginOK");      response.put("id", String.valueOf(loginUser.getUserId()));      response.put("name", loginUser.getName());           }catch(LoginException e){      response.put("cmd", "loginKO");      response.put("err", e.getMessage());     } 
 
 
   }else{     response.put("cmd", "loginKO");     response.put("err", "error password");    }    recipients.add(chan);    this.sendResponse(response, -1, null, recipients);    this.helper.sendRoomList(chan);   }     } 
} 


其中的一些不明白的地方,大家到网上自己查询。 
二,将写好的 MyExtension.java 编译成 MyExtension.class 文件。我的 SmartFoxServer 安装在 D 盘下。所以将编 译好的文件拷贝到 D:\Program Files\SmartFoxServerPRO_1.6.6\Server\javaExtensions\com\song\unity3d \login 文 件夹下. 
三,打开 D:\Program Files\SmartFoxServerPRO_1.6.6\Server 目录下的 config.xml 文件。将如下代码拷贝 到<Zones></Zones>区间。保存后重启 SmartFoxServer 服 务器. 
<Zone name="firstZone" uCountUpdate="true" buddyList="20" maxUsers="4000" customLogin="true">     <Rooms>      <Room name="The Hall" maxUsers="50" isPrivate="false" isTemp="false" autoJoin="true" uCountUpdate="true" />     </Rooms>         <Extensions>      <Extension name="firstSFS" className="com.song.unity3d.login.MyExtension" type="java" />     </Extensions>    </Zone> 


四,在 Unity3d 中创建一个 C#文件。代码如下所示. 
using UnityEngine; 
using System; 
using System.Collections; 
 
 
  
using SmartFoxClientAPI; 
using SmartFoxClientAPI.Util; 
using SmartFoxClientAPI.Data; 
  
/* 
 * @author songvery 
 * @version 2011-03-09-01 
 * @infomation 请输入相同的用户名和密码,服务器端扩展做的是用户名=密码 的验证简单验证 
 * */ 
public class ConnectionGUI: MonoBehaviour { 
  
 private SmartFoxClient smartFox; 
  
 private bool shuttingDown = false; 
  
 private string serverName = "127.0.0.1";//服务器 IP 
  
 private int serverPort = 9339;//服务器端口号 
  
 private string zone = "firstZone"; 
  
 private string username="songvery";//用户名 
 
 
  
 private string password="";//密码 
  
 private string errorMessage = "";//错误信息 
  
 private string extensionName="";//服务器端扩展名 
  
 /* 
  * 构造函数 
  * */ 
 public ConnectionGUI(){ 
  extensionName="firstSFS"; 
 } 
  
 void OnApplicationQuit() { 
  shuttingDown = true; 
 } 
  
 private bool connectionAttempt = false; 
  
  
 // Use this for initialization 
 void Start () { 
  
 
 
  Application.runInBackground = true; 
   
  bool debug=true; 
   
  if(SmartFox.IsInitialized()){ 
    
   smartFox=SmartFox.Connection; 
    
  }else{ 
    
   try{ 
    smartFox=new SmartFoxClient(debug); 
    smartFox.runInQueueMode = true; 
   }catch(Exception e){ 
    errorMessage=e.ToString(); 
   } 
  } 
   
  SFSEvent.onConnection += OnConnection; 
  SFSEvent.onConnectionLost += OnConnectionLost; 
  SFSEvent.onLogin += OnLogin; 
  SFSEvent.onRoomListUpdate += OnRoomListUpdate; 
  SFSEvent.onDebugMessage += OnDebugMessage; 
 
 
  SFSEvent.onExtensionResponse += OnExtensionResponse;//注册一个 SFSEvent 事 件 
 } 
  
 void FixedUpdate() { 
  smartFox.ProcessEventQueue(); 
 } 
  
 private void UnregisterSFSSceneCallBacks(){ 
  SFSEvent.onConnection-=OnConnection; 
  SFSEvent.onConnectionLost-=OnConnectionLost; 
  SFSEvent.onLogin-=OnLogin; 
  SFSEvent.onRoomListUpdate-=OnRoomListUpdate; 
  SFSEvent.onDebugMessage-=OnDebugMessage; 
  SFSEvent.onExtensionResponse -= OnExtensionResponse; 
 } 
  
 void OnConnection(bool success,string error){ 
  if(success){ 
   SmartFox.Connection=smartFox; 
  }else{ 
   errorMessage=error; 
  } 
 } 
 
 
  
 void OnConnectionLost(){ 
  Debug.Log("OnConnectionLost"); 
  errorMessage="connection lost/No connnection to server"; 
 } 
  
 void OnDebugMessage(string message){ 
  Debug.Log("SFSDEBUG ----"+message); 
 } 
  
 /** 
  * 尝试与服务器的连接 
  * */ 
 void ConnectToServer(){ 
  try{ 
   smartFox.Connect(serverName,serverPort); 
  }catch(Exception e){ 
   errorMessage=e.ToString(); 
   //Application.ExternalEval ("history.go(-1);"); 
  } 
 } 
  
 void OnGUI() { 
  
 
 
  if (!connectionAttempt) { 
    
    connectionAttempt = true; 
    ConnectToServer();  
  } 
  else if (smartFox.IsConnected()) { 
   // Login 
   GUI.Label(new Rect(10, 116, 100, 100), "Username: "); 
  
   username = GUI.TextField(new Rect(100, 116, 200, 20), this.username, 25); 
    
   GUI.Label(new Rect(10,156,100,100),"Password: "); 
  
   password=GUI.PasswordField(new Rect(100,156,200,20),this.password,"*"[0],25); 
  
   GUI.Label(new Rect(10, 190, 100, 100), errorMessage); 
  
   if ( GUI.Button(new Rect(100, 230, 100, 24), "Login")  || (Event.current.type == EventType.keyDown && Event.current.character == '\n')) { 
     
    smartFox.Login(zone, username, password); 
   } 
  
  } else { 
 
 
   GUI.Label(new Rect(10, 150, 100, 100), "Waiting for connection"); 
   GUI.Label(new Rect(10, 190, 100, 100), errorMessage); 
  } 
 } 
  
  
 void OnLogin(bool success, string name, string error){ 
  if(success){ 
   Debug.Log("Hello:Welcome "+name); 
  }else{ 
   errorMessage=error; 
  } 
   
 } 
  
 void OnRoomListUpdate(Hashtable roomList){ 
  UnregisterSFSSceneCallBacks(); 
  Application.LoadLevel("game"); 
 } 
  
 /** 
  * 从服务器端扩展接收的信息处理 
  * */ 
 public void OnExtensionResponse(object data, string type) { 
 
 
 
  // We only use XML based messages in this tutorial, so ignore string and json types 
  if ( type == SmartFoxClient.XTMSG_TYPE_XML ) { 
   // For XML based communication the data object is a SFSObject 
   SFSObject dataObject = (SFSObject)data; 
   switch(dataObject.GetString("cmd")){ 
   case "loginOK": 
     //说明用户登录成功 
    Debug.Log("You pass validation!"); 
    smartFox.myUserName = dataObject.GetString("name");//服务器端传递的用户名 
      smartFox.myUserId = int.Parse(dataObject.GetString("id"));//服务器端传递的 ID 
    break; 
   case "loginKO": 
     //登录失败,在这可以做相应的处理,如跳转到注册的页面。。。 
    errorMessage="You not pass validation!"; 
    break; 
   } 
  } 
 } 
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值