public void OnEventRaised(LNSClient from, ushort eventCode, LNSReader reader, DeliveryMethod deliveryMethod) { if (messageReceiver != null) { messageReceiver(reader.GetString()); } }
public bool CanReconnect(LNSClient client) { lock (thelock) { return(disconnectedClients.Contains(client.id)); } }
private void OnPlayerConnected(LNSClient client) { Debug.LogFormat("OnPlayerConnected {0} {1} {2}", client.id, client.displayName, client.platform.ToString()); writer.Reset(); writer.Put(player.color); connector.RaiseEventOnClient(client, 0, writer, DeliveryMethod.ReliableOrdered); }
public void OnEventRaised(LNSClient from, ushort eventCode, LNSReader reader, DeliveryMethod deliveryMethod) { if (eventCode == 0) { Color color = reader.GetColor(); if (others.ContainsKey(from.id)) { Clone o = others[from.id]; o.GetComponent <Clone>().SetColor(color); o.gameObject.name = from.id + "_" + from.displayName; } else { GameObject o = Instantiate(clonePrefab); o.GetComponent <Clone>().SetColor(color); o.name = from.id + "_" + from.displayName; others.Add(from.id, o.GetComponent <Clone>()); } } else if (eventCode == 1) { string playerid = from.id; Vector3 pos = reader.GetVector3(); Quaternion rot = reader.GetQuaternion(); //long timestamp = reader.GetLong(); //Debug.Log(timestamp); //float delay = (float)(System.DateTime.UtcNow - System.DateTime.FromFileTimeUtc(timestamp)).TotalMilliseconds; //if (delay > 400) //{ // //Discard old packet // return; //} if (others.ContainsKey(playerid)) { others[playerid].SetTarget(pos, rot); } } else if (eventCode == 2) { if (others.ContainsKey(from.id)) { Vector3 pos = reader.GetVector3(); Quaternion rot = reader.GetQuaternion(); others[from.id].ShootBulletAt(pos, rot); } } else if (eventCode == 3) { player.transform.position += Vector3.up; } else if (eventCode == 10) { if (others.ContainsKey(from.id)) { others[from.id].audioReceiver.Play(reader.GetInt(), reader.GetInt(), reader.GetRemainingBytes()); } } }
public void AddPlayer(LNSClient client) { lock (thelock) { if (roomParameters.isQuadTreeAllowed) { quadTree.Insert(client); } clients.Add(client); if (disconnectedClients.Contains(client.id)) { disconnectedClients.Remove(client.id); } } SendPlayerConnectedEvent(client); // player connected event if (clients.Count == 1) { masterClient = client; SendMasterPlayerChangedEvent(); //Send master client changed event } else { lock (thelock) { for (int i = 0; i < clients.Count; i++) { if (clients[i].id != client.id) { client.writer.Reset(); client.writer.Put(LNSConstants.CLIENT_EVT_ROOM_PLAYER_CONNECTED); client.writer.Put(clients[i].id); client.writer.Put(clients[i].displayname); client.writer.Put((byte)clients[i].platform); client.writer.Put(clients[i].networkid); client.peer.Send(client.writer, DeliveryMethod.ReliableOrdered); } } writer.Reset(); writer.Put(LNSConstants.CLIENT_EVT_ROOM_MASTERCLIENT_CHANGED); writer.Put(masterClient.id); client.peer.Send(writer, DeliveryMethod.ReliableOrdered); foreach (var cachedData in persistentData) { writer.Reset(); writer.Put(LNSConstants.CLIENT_EVT_ROOM_CACHE_DATA); writer.Put(cachedData.Key); writer.Put(cachedData.Value); client.peer.Send(writer, DeliveryMethod.ReliableOrdered); } } } }
private void OnPlayerDisconnected(LNSClient client) { Debug.Log("OnPlayerDisconnected " + client.id); if (others.ContainsKey(client.id)) { GameObject.Destroy(others[client.id].gameObject); others.Remove(client.id); } }
public void SendPlayerDisconnectedEvent(LNSClient client) { lock (thelock) { writer.Reset(); writer.Put(LNSConstants.CLIENT_EVT_ROOM_PLAYER_DISCONNECTED); writer.Put(client.id); for (int i = 0; i < clients.Count; i++) { clients[i].peer.Send(writer, DeliveryMethod.ReliableOrdered); } } }
public void RemovePlayer(LNSClient client) { string clientid = client.id; lock (thelock) { if (roomParameters.isQuadTreeAllowed) { quadTree.Remove(client); } clients.Remove(client); if (!disconnectedClients.Contains(clientid)) { disconnectedClients.Add(clientid); } if (clients.Count == 0) { new Thread(() => { try { int waited = 0; while (waited < roomParameters.idleLife) { if (clients.Count > 0) // check if someone rejoined { return; } Thread.Sleep(1000); waited += 1; } assocGame.RemoveRoom(this); } catch { } }).Start(); return; } } SendPlayerDisconnectedEvent(client); if (clientid == masterClient.id) { masterClient = clients[0]; SendMasterPlayerChangedEvent(); //Send master client changed event } }
public LNSConnector(LNSClientParameters clientParameters, LNSConnectSettings settings, ILNSDataReceiver dataReceiver) { this.clientParameters = clientParameters; this.settings = settings; this.dataReceiver = dataReceiver; this.threadDispatcher = LNSMainThreadDispatcher.GetInstance(); localClient = new LNSClient(); clientDataWriter = new NetDataWriter(); writer = new NetDataWriter(); this.settings.Validate(); EventBasedNetListener listener = new EventBasedNetListener(); client = new NetManager(listener); SetClientId(this.clientParameters.id); //Write Client Data clientDataWriter.Put(this.settings.serverSecurityKey); clientDataWriter.Put(this.clientParameters.id); clientDataWriter.Put(this.clientParameters.displayName); clientDataWriter.Put(this.settings.gameKey); clientDataWriter.Put(this.settings.gameVersion); clientDataWriter.Put(this.settings.platform); //List to receiveEvent listener.PeerConnectedEvent += Listener_PeerConnectedEvent; listener.PeerDisconnectedEvent += Listener_PeerDisconnectedEvent; listener.NetworkReceiveEvent += Listener_NetworkReceiveEvent; listener.NetworkErrorEvent += Listener_NetworkErrorEvent; listener.NetworkReceiveUnconnectedEvent += Listener_NetworkReceiveUnconnectedEvent; }
public void OnEventRaised(LNSClient from, ushort eventCode, LNSReader reader, DeliveryMethod deliveryMethod) { totalDataTransfered += reader.RawDataSize; if (Time.time - timeDataCountStarted > 1) { dataTransferPerSec = (float)totalDataTransfered / (Time.time - timeDataCountStarted); timeDataCountStarted = Time.time; totalDataTransfered = 0; } if (eventCode == 0) { if (!remoteClones.ContainsKey(from.id)) { GameObject clone = GameObject.Instantiate(clonePrefab, clonePrefab.transform.parent, true); clone.SetActive(true); clone.name = "Clone_" + from.id; remoteClones.Add(from.id, clone.transform); } remoteClones[from.id].localPosition = reader.GetVector3(); } }
public void SendPlayerConnectedEvent(LNSClient client) { //UnityEngine.Debug.Log("SendPlayerConnectedEvent: "+client.displayname); lock (thelock) { writer.Reset(); writer.Put(LNSConstants.CLIENT_EVT_ROOM_PLAYER_CONNECTED); //UnityEngine.Debug.Log("SendPlayerConnectedEvent " + client.id + " "+client.displayname); writer.Put(client.id); writer.Put(client.displayname); writer.Put((byte)client.platform); writer.Put(client.networkid); for (int i = 0; i < clients.Count; i++) { if (clients[i].networkid != client.networkid) { clients[i].peer.Send(writer, DeliveryMethod.ReliableOrdered); } } } }
public void ProcessReceivedData(LNSClient from, byte instructionCode, NetPacketReader reader, DeliveryMethod deliveryMethod) { byte code = instructionCode; if (code == LNSConstants.SERVER_EVT_LOCK_ROOM) { if (from.id == masterClient.id) { isOpen = false; } return; } else if (code == LNSConstants.SERVER_EVT_UNLOCK_ROOM) { if (from.id == masterClient.id) { isOpen = true; } return; } else if (code == LNSConstants.SERVER_EVT_RAW_DATA_TO_CLIENT) { string targetid = reader.GetString(); lock (thelock) { for (int i = 0; i < clients.Count; i++) { var targetClient = clients.Find(client => client.id == targetid); writer.Reset(); writer.Put(LNSConstants.CLIENT_EVT_ROOM_RAW); writer.Put(from.id); writer.Put(reader.GetRemainingBytes()); targetClient.peer.Send(writer, deliveryMethod); } } } else if (code == LNSConstants.SERVER_EVT_RAW_DATA_TO_NEARBY_CLIENTS) { if (roomParameters.isQuadTreeAllowed) { Rect searchRect = new Rect(reader.GetFloat(), reader.GetFloat(), reader.GetFloat(), reader.GetFloat()); from.position = searchRect.center; lock (thelock) { quadTreeSearchResults.Clear(); quadTree.RetrieveObjectsInAreaNoAlloc(searchRect, ref quadTreeSearchResults); //Debug.LogFormat("From {0} - Search Rect {1},{2} {3},{4} - Found: {5}", from.id, searchRect.center.x, searchRect.center.x, searchRect.width, searchRect.height, quadTreeSearchResults.Count); writer.Reset(); writer.Put(LNSConstants.CLIENT_EVT_ROOM_RAW); writer.Put(from.id); writer.Put(reader.GetRemainingBytes()); for (int i = 0; i < quadTreeSearchResults.Count; i++) { if (quadTreeSearchResults[i].networkid != from.networkid) { quadTreeSearchResults[i].peer.Send(writer, deliveryMethod); } } } } } else if (code == LNSConstants.SERVER_EVT_RAW_DATA_CACHE) { lock (thelock) { string key = reader.GetString(); byte[] value = reader.GetRemainingBytes(); if (value.Length <= 1000) { if (persistentData.ContainsKey(key)) { persistentData[key] = value; } else { persistentData.Add(key, value); } writer.Reset(); writer.Put(LNSConstants.CLIENT_EVT_ROOM_CACHE_DATA); writer.Put(key); writer.Put(value); for (int i = 0; i < clients.Count; i++) { clients[i].peer.Send(writer, DeliveryMethod.ReliableOrdered); } } } } else { lock (thelock) { writer.Reset(); writer.Put(LNSConstants.CLIENT_EVT_ROOM_RAW); writer.Put(from.id); writer.Put(reader.GetRemainingBytes()); for (int i = 0; i < clients.Count; i++) { if (clients[i].networkid != from.networkid) { clients[i].peer.Send(writer, deliveryMethod); } } } } }
//protected void WritePlayerData(NetDataWriter writer) //{ // writer.Put(id); // writer.Put(displayName); // writer.Put(this.settings.gameKey); // writer.Put(this.settings.gameVersion); // writer.Put(this.settings.platform); //} private void Listener_NetworkReceiveEvent(NetPeer peer, NetPacketReader packetReader, DeliveryMethod deliveryMethod) { byte clientInstruction = packetReader.GetByte(); if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_LIST) { if (roomList == null) { roomList = new LNSRoomList(); } JsonUtility.FromJsonOverwrite(packetReader.GetString(), roomList); if (onRoomListReceived != null) { threadDispatcher.Add(() => onRoomListReceived(roomList)); } } else if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_CREATED) { isInActiveRoom = true; _lastConnectedRoom = packetReader.GetString(); if (onRoomCreated != null) { threadDispatcher.Add(() => onRoomCreated()); } } else if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_DISCONNECTED) { if (onDisconnectedFromRoom != null) { threadDispatcher.Add(() => onDisconnectedFromRoom()); } } else if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_FAILED_CREATE) { byte reason = packetReader.GetByte(); if (onRoomCreateFailed != null) { threadDispatcher.Add(() => onRoomCreateFailed((ROOM_FAILURE_CODE)reason)); } } else if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_FAILED_JOIN) { byte reason = packetReader.GetByte(); if (onRoomJoinFailed != null) { threadDispatcher.Add(() => onRoomJoinFailed((ROOM_FAILURE_CODE)reason)); } } else if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_FAILED_REJOIN) { byte reason = packetReader.GetByte(); if (onRoomRejoinFailed != null) { threadDispatcher.Add(() => onRoomRejoinFailed((ROOM_FAILURE_CODE)reason)); } } else if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_JOINED) { isInActiveRoom = true; _lastConnectedRoom = packetReader.GetString(); if (onRoomJoined != null) { threadDispatcher.Add(() => onRoomJoined()); } } else if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_REJOINED) { isInActiveRoom = true; _lastConnectedRoom = packetReader.GetString(); if (onRoomRejoined != null) { threadDispatcher.Add(() => onRoomRejoined()); } } else if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_FAILED_RANDOM_JOIN) { isInActiveRoom = false; if (onRandomRoomJoinFailed != null) { threadDispatcher.Add(() => onRandomRoomJoinFailed()); } } else if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_MASTERCLIENT_CHANGED) { _lastConnectedRoomMasterClient = packetReader.GetString(); localClient.isMasterClient = isLocalPlayerMasterClient = (_lastConnectedRoomMasterClient == id); if (onMasterClientUpdated != null) { try { if (isLocalPlayerMasterClient) { threadDispatcher.Add(() => { onMasterClientUpdated(localClient); }); } else { for (int i = 0; i < clients.Count; i++) { if (clients[i].id == _lastConnectedRoomMasterClient) { clients[i].isMasterClient = true; LNSClient client = clients[i]; threadDispatcher.Add(() => { onMasterClientUpdated(client); }); } else { clients[i].isMasterClient = false; } } } }catch (System.Exception ex) { Debug.LogError(ex.Message + " " + ex.StackTrace); } } } else if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_PLAYER_CONNECTED) { string client_id = packetReader.GetString(); string client_displayName = packetReader.GetString(); CLIENT_PLATFORM client_platform = (CLIENT_PLATFORM)packetReader.GetByte(); int client_netID = packetReader.GetInt(); LNSClient client = null; for (int i = 0; i < clients.Count; i++) { if (clients[i].id == client_id) { client = clients[i]; client.displayName = client_displayName; client.platform = client_platform; client.networkID = client_netID; break; } } if (client == null) { client = new LNSClient(); client.id = client_id; client.displayName = client_displayName; client.platform = client_platform; client.networkID = client_netID; clients.Add(client); } client.isConnected = true; if (onPlayerConnected != null) { threadDispatcher.Add(() => { onPlayerConnected(client); }); } } else if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_PLAYER_DISCONNECTED) { string client_id = packetReader.GetString(); for (int i = 0; i < clients.Count; i++) { if (clients[i].id == client_id) { clients[i].isConnected = false; if (onPlayerDisconnected != null) { threadDispatcher.Add(() => { onPlayerDisconnected(clients[i]); }); } return; } } } else if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_CACHE_DATA) { LNSReader reader = LNSReader.GetFromPool(); string key = packetReader.GetString(); byte[] data = packetReader.GetRemainingBytes(); reader.SetSource(data); if (persistentData.ContainsKey(key)) { persistentData[key] = data; } else { persistentData.Add(key, data); } if (dataReceiver != null) { threadDispatcher.Add(() => { try { dataReceiver.OnCachedDataReceived(key, reader); } catch (System.Exception ex) { Debug.LogError(ex.Message + " " + ex.StackTrace); } reader.Recycle(); }); } } else if (clientInstruction == LNSConstants.CLIENT_EVT_ROOM_RAW) { string fromid = packetReader.GetString(); for (int i = 0; i < clients.Count; i++) { if (fromid == clients[i].id) { if (dataReceiver != null) { ushort eventCode = packetReader.GetUShort(); LNSReader reader = LNSReader.GetFromPool(); LNSClient fromClient = clients[i]; DeliveryMethod _deliveryMethod = deliveryMethod; reader.SetSource(packetReader.GetRemainingBytes()); threadDispatcher.Add(() => { try { dataReceiver.OnEventRaised(fromClient, eventCode, reader, _deliveryMethod); } catch (System.Exception ex) { Debug.LogError(ex.Message + " " + ex.StackTrace); } reader.Recycle(); }); } break; } } } packetReader.Recycle(); }
//public bool RaiseEventOnAllAndCache(ushort eventCode, LNSWriter m_writer) //{ // if (isConnected && isInActiveRoom) // { // new Thread(() => // { // lock (thelock) // { // writer.Reset(); // writer.Put(LNSConstants.SERVER_EVT_RAW_DATA_CACHE); // writer.Put(eventCode); // writer.Put(m_writer.Data); // peer.Send(writer,DeliveryMethod.ReliableOrdered); // } // }).Start(); // return true; // } // return false; //} //public bool RaiseEventRemoveMyCache() //{ // if (isConnected && isInActiveRoom) // { // new Thread(() => // { // lock (thelock) // { // //writer.Reset(); // //writer.Put(LNSConstants.SERVER_EVT_RAW_DATA_CACHE); // //writer.Put(eventCode); // //writer.Put(m_writer.Data); // //peer.Send(writer, DeliveryMethod.ReliableOrdered); // } // }).Start(); // return true; // } // return false; //} //public bool RaiseEventRemoveAllCache() //{ // if (isConnected && isInActiveRoom && isLocalPlayerMasterClient) // { // new Thread(() => // { // lock (thelock) // { // writer.Reset(); // writer.Put(LNSConstants.SERVER_EVT_REMOVE_ALL_CACHE); // peer.Send(writer, DeliveryMethod.ReliableOrdered); // //writer.Put(eventCode); // //writer.Put(m_writer.Data); // } // }).Start(); // return true; // } // return false; //} public bool RaiseEventOnClient(LNSClient client, ushort eventCode, LNSWriter m_writer, DeliveryMethod deliveryMethod) { return(RaiseEventOnClient(client.id, eventCode, m_writer, deliveryMethod)); }
public void Start() { new Thread(() => { EventBasedNetListener listener = new EventBasedNetListener(); NetManager server = new NetManager(listener); server.Start(this.port); Debug.Log("Server Started"); listener.ConnectionRequestEvent += request => { Debug.Log("connection request recieved"); lock (thelock) { string clientKey = request.Data.GetString(); if (clientKey == "RJPROZ_IS_MASTER") { } else if (clientKey != this.key) { NetDataWriter writer = new NetDataWriter(false, 1); writer.Put(LNSConstants.CLIENT_EVT_UNAUTHORIZED_CONNECTION); request.Reject(writer); } else { try { string userid = request.Data.GetString(); string displayName = request.Data.GetString(); string gameKey = request.Data.GetString(); string version = request.Data.GetString(); CLIENT_PLATFORM platform = (CLIENT_PLATFORM)request.Data.GetByte(); if (string.IsNullOrEmpty(gameKey) || !gameKey.Contains("hybriona") || string.IsNullOrEmpty(userid)) { NetDataWriter writer = new NetDataWriter(); writer.Put(LNSConstants.CLIENT_EVT_UNAUTHORIZED_GAME); request.Reject(writer); } else if (connectedClientIds.Contains(userid)) { NetDataWriter writer = new NetDataWriter(false, 1); writer.Put(LNSConstants.CLIENT_EVT_USER_ALREADY_CONNECTED); request.Reject(writer); } else { NetPeer peer = request.Accept(); LNSClient client = null; if (!clients.ContainsKey(peer.Id)) { client = new LNSClient(peer); clients.Add(peer.Id, client); } else { client = clients[peer.Id]; client.peer = peer; } client.networkid = peer.Id; client.id = userid; client.displayname = displayName; client.gameKey = gameKey; client.gameVersion = version; client.platform = platform; connectedClientIds.Add(userid); Debug.Log("Connected : " + peer.Id + " | Total clients: " + clients.Count); Log(string.Format("Connected {0} {1} {2} {3}", gameKey, displayName, platform, userid)); } } catch { NetDataWriter writer = new NetDataWriter(false, 1); writer.Put(LNSConstants.CLIENT_EVT_SERVER_EXECEPTION); request.Reject(writer); } } } }; //listener.PeerConnectedEvent += peer => //{ // lock (thelock) // { // try // { // } // catch(System.Exception ex) // { // Debug.LogError(ex.Message + " - "+ex.StackTrace); // } // } //}; listener.NetworkReceiveEvent += (NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod) => { int peerId = peer.Id; LNSClient client = clients[peerId]; byte instruction = reader.GetByte(); if (client.connectedRoom == null) { string gameKey = client.gameKey; string version = client.gameVersion; CLIENT_PLATFORM platform = client.platform; LNSGame game = null; if (games.ContainsKey(gameKey)) { game = games[gameKey]; } else { game = new LNSGame(gameKey, this); games.Add(game.gameKey, game); } Dictionary <string, LNSRoom> rooms = game.rooms; if (instruction == LNSConstants.SERVER_EVT_CREATE_ROOM) { //Debug.Log("Create room"); string roomid = reader.GetString(); LNSCreateRoomParameters roomParameters = LNSCreateRoomParameters.FromReader(reader); lock (thelock) { if (rooms.ContainsKey(roomid.ToLower())) { client.SendFailedToCreateRoomEvent(ROOM_FAILURE_CODE.ROOM_ALREADY_EXIST); //: Room creation failed } else { LNSRoom room = new LNSRoom(roomid); room.gameKey = gameKey; room.gameVersion = version; room.primaryPlatform = (byte)platform; room.roomParameters = roomParameters; room.assocGame = game; room.Prepare(); rooms.Add(roomid.ToLower(), room); client.connectedRoom = room; client.SendRoomCreatedEvent(); //: Room created room.AddPlayer(client); Log("Room created " + room.id, client); } } } else if (instruction == LNSConstants.SERVER_EVT_CREATE_OR_JOIN_ROOM) { string roomid = reader.GetString(); int maxPlayers = reader.GetInt(); lock (thelock) { if (!rooms.ContainsKey(roomid.ToLower())) { LNSRoom room = new LNSRoom(roomid); room.gameKey = gameKey; room.gameVersion = version; room.primaryPlatform = (byte)platform; room.roomParameters = new LNSCreateRoomParameters(); room.roomParameters.maxPlayers = maxPlayers; room.assocGame = game; room.Prepare(); rooms.Add(roomid.ToLower(), room); client.connectedRoom = room; client.SendRoomCreatedEvent(); //: Room created Event room.AddPlayer(client); Log("Room created " + room.id, client); } else { LNSRoom room = rooms[roomid.ToLower()]; if (room.gameVersion != client.gameVersion) { client.SendRoomFailedToJoinEvent(ROOM_FAILURE_CODE.VERSION_MISMATCH); } else if (!room.isOpen) { client.SendRoomFailedToJoinEvent(ROOM_FAILURE_CODE.ROOM_LOCKED); // Room join failed } else if (room.playerCount >= room.roomParameters.maxPlayers) { client.SendRoomFailedToJoinEvent(ROOM_FAILURE_CODE.ROOM_FULL); } else { client.connectedRoom = room; client.SendRoomJoinedEvent();//: Room joined room.AddPlayer(client); Log("Room joined " + room.id, client); } } } } else if (instruction == LNSConstants.SERVER_EVT_JOIN_ROOM) { string roomid = reader.GetString(); bool hasPassword = reader.GetBool(); string password = null; if (hasPassword) { password = reader.GetString(); } lock (thelock) { if (rooms.ContainsKey(roomid.ToLower())) { LNSRoom room = rooms[roomid.ToLower()]; if (room.gameVersion != client.gameVersion) { client.SendRoomFailedToJoinEvent(ROOM_FAILURE_CODE.VERSION_MISMATCH); } else if ((room.hasPassword && password == null) || (room.hasPassword && room.roomParameters.password != password)) { client.SendRoomFailedToJoinEvent(ROOM_FAILURE_CODE.PASSWORD_MISMATCH); } else if (!room.isOpen) { client.SendRoomFailedToJoinEvent(ROOM_FAILURE_CODE.ROOM_LOCKED); } else if (room.playerCount >= room.roomParameters.maxPlayers) { client.SendRoomFailedToJoinEvent(ROOM_FAILURE_CODE.ROOM_FULL); } else { client.connectedRoom = room; client.SendRoomJoinedEvent(); //: Room Joined room.AddPlayer(client); Log("Room joined " + room.id, client); } } else { client.SendRoomFailedToJoinEvent(ROOM_FAILURE_CODE.ROOM_DOESNT_EXIST); // Room join failed } } } else if (instruction == LNSConstants.SERVER_EVT_JOIN_RANDOM_ROOM) { LNSJoinRoomFilter filter = LNSJoinRoomFilter.FromReader(reader); lock (thelock) { bool found = false; foreach (var roomKV in rooms) { LNSRoom room = roomKV.Value; //Debug.Log("is room param null " + (room.roomParameters == null)); if (room.roomParameters.isPublic && room.gameVersion == client.gameVersion && !room.hasPassword && room.isOpen && room.playerCount < room.roomParameters.maxPlayers) { if (filter == null || room.IsFilterMatch(filter)) { client.connectedRoom = room; client.SendRoomJoinedEvent(); //: Room Joined room.AddPlayer(client); Log("Room random joined " + room.id, client); found = true; break; } } } if (!found) { client.SendRoomFailedToRandomJoin(); // Room join failed } } } else if (instruction == LNSConstants.SERVER_EVT_REJOIN_ROOM) { string roomid = reader.GetString(); lock (thelock) { if (rooms.ContainsKey(roomid.ToLower())) { LNSRoom room = rooms[roomid.ToLower()]; if (room.playerCount >= room.roomParameters.maxPlayers) { client.SendRoomFailedToReJoinEvent(ROOM_FAILURE_CODE.ROOM_FULL); } else if (!room.CanReconnect(client)) { client.SendRoomFailedToReJoinEvent(ROOM_FAILURE_CODE.REJOIN_NOT_AUTHORIZED); } else { client.connectedRoom = room; client.SendRoomReJoinedEvent(); //: Room ReJoined room.AddPlayer(client); Log("Room rejoined " + room.id, client); } } else { client.SendRoomFailedToReJoinEvent(ROOM_FAILURE_CODE.ROOM_DOESNT_EXIST); // Room join failed } } } else if (instruction == LNSConstants.SERVER_EVT_FETCH_ROOM_LIST) { LNSJoinRoomFilter filter = LNSJoinRoomFilter.FromReader(reader); lock (thelock) { LNSRoomList roomList = new LNSRoomList(); int counter = 0; foreach (var roomKV in rooms) { LNSRoom room = roomKV.Value; //Debug.Log("is room param null " + (room.roomParameters == null)); if (room.roomParameters.isPublic && room.gameVersion == client.gameVersion && room.isOpen && room.playerCount < room.roomParameters.maxPlayers) { if (filter == null || room.IsFilterMatch(filter)) { string roomid = room.id; bool roomHasPassword = room.hasPassword; int currentPlayerCount = room.playerCount; int maxPlayers = room.roomParameters.maxPlayers; LNSRoomList.RoomData roomData = new LNSRoomList.RoomData(); roomData.id = roomid; roomData.hasPassword = roomHasPassword; roomData.playerCount = currentPlayerCount; roomData.maxPlayers = maxPlayers; roomList.list.Add(roomData); counter++; if (counter >= 100) { break; } } } } client.SendRoomList(roomList); roomList.list = null; roomList = null; } } } else { if (instruction == LNSConstants.SERVER_EVT_LEAVE_ROOM) { client.SendDisconnectEvent(true); client.connectedRoom = null; } else { client.connectedRoom.ProcessReceivedData(client, instruction, reader, deliveryMethod); } } reader.Recycle(); }; listener.PeerDisconnectedEvent += (NetPeer peer, DisconnectInfo disconnectInfo) => { lock (thelock) { int peerId = peer.Id; if (clients.ContainsKey(peerId)) { LNSClient client = clients[peerId]; client.SendDisconnectEvent(false); if (connectedClientIds.Contains(client.id)) { connectedClientIds.Remove(client.id); } client.Dispose(); clients.Remove(peerId); } } Debug.Log("Disconnected : " + peer.Id); }; while (true) { server.PollEvents(); Thread.Sleep(threadWaitMilliseconds); // 30 times per second } }).Start(); }
public void Log(string data, LNSClient client) { System.IO.File.AppendAllText(logFilePath, System.DateTime.Now + "\n" + data + string.Format(" by {0} {1} {2} {3}", client.gameKey, client.displayname, client.platform, client.id) + "\n\n"); }