//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 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(); }