4 * Copyright 2015 eddie.
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 package uk.ac.ntu.n0521366.wsyd.libs.net;
26 import java.util.Random;
27 import java.util.concurrent.ConcurrentHashMap;
33 public class NetworkStreamManager implements NetworkSocketClosing {
35 public static final long SERVERSOCIAL = -98;
37 public static final long SERVERCHAT = -99;
39 static final long TEMPCLIENT = -200;
46 public ConcurrentHashMap<Long, NetworkStream> _tcpStreams;
48 public NetworkStreamManager() {
49 random = new Random();
50 _tcpStreams = new ConcurrentHashMap<Long, NetworkStream>();
53 public long addStream(long userID, NetworkStream netStream) {
56 if (netStream != null) {
57 if (!_tcpStreams.containsKey(userID)) {
61 tempKey = createTempKey();
62 } while (_tcpStreams.containsKey(tempKey));
63 _tcpStreams.put(tempKey, netStream);
65 netStream._key = tempKey;
67 System.err.println("Added new stream with key: " + tempKey);
70 if ((userID < 0 && userID > TEMPCLIENT) || userID > 0) {
71 _tcpStreams.put(userID, netStream);
73 netStream._key = userID;
75 System.err.println("Added new stream with predefined key: " + userID);
84 public boolean updateKey(long oldID, long newID) {
85 boolean result = false;
87 if (!_tcpStreams.containsKey(newID)) {
88 if (_tcpStreams.containsKey(oldID)) {
89 NetworkStream temp = _tcpStreams.get(oldID);
91 _tcpStreams.put(newID, temp);
92 System.err.println("Added new stream with key: " + newID);
93 _tcpStreams.remove(oldID);
102 private long createTempKey() {
103 return TEMPCLIENT + -random.nextInt(1000000);
107 public boolean canCloseSocket(long key) {
108 boolean result = false;
110 if (_tcpStreams.containsKey(key)) {
111 _tcpStreams.remove(key);
113 System.err.println("Removed stream with key: " + key);