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 static final int SERVERSOCIAL = -98;
37 static final int SERVERCHAT = -99;
39 static final int TEMPCLIENT = -200;
46 public ConcurrentHashMap<Integer, NetworkStream> _tcpStreams;
48 public NetworkStreamManager() {
49 random = new Random();
50 _tcpStreams = new ConcurrentHashMap<Integer, NetworkStream>();
53 public int addStream(int 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 System.err.println("Added new stream with key: " + tempKey);
68 if ((userID < 0 && userID > TEMPCLIENT) || userID > 0) {
69 _tcpStreams.put(userID, netStream);
79 public boolean updateKey(int oldID, int newID) {
80 boolean result = false;
82 if (!_tcpStreams.containsKey(newID)) {
83 if (_tcpStreams.containsKey(oldID)) {
84 _tcpStreams.put(newID, _tcpStreams.get(oldID));
85 _tcpStreams.remove(oldID);
94 private int createTempKey() {
95 return TEMPCLIENT + -random.nextInt(1000000);
99 public boolean canCloseSocket(int key) {
100 boolean result = false;
102 if (_tcpStreams.containsKey(key)) {
103 _tcpStreams.remove(key);
105 System.err.println("Removed key: " + key);