/*string.Concat("./Global/", PortReleaseGuid)*/ /// <summary> /// 查找一个端口 /// </summary> /// <param name="startPort"></param> /// <returns></returns> public static int FindOneAvailableTCPPort(int startPort) { return(NetworkUtil.FindAvailableTCPPorts(startPort, 1)[0]); }
//通过客户端的id请求,分配好服务端端口和appid交给客户端 //arrange ConfigId from top 4 bytes which received from client. //response: // 2 1 1 1 1 ...N // clientid appid port appid2 port2 //request: // 2 2 // clientid count // methodType value = 0 public byte[] ArrageConfigIds(byte[] appRequestBytes) { // byte[] arrangedBytes = new byte[256]; ClientModel clientModel = new ClientModel(); int clientId = (appRequestBytes[0] << 8) + appRequestBytes[1]; int appCount = (int)appRequestBytes[2]; if (clientId == 0) { lock (_lockObject) { byte[] tempClientIdBytes = new byte[2]; //分配clientid for (int i = 0; i < 10000; i++) { _rand.NextBytes(tempClientIdBytes); int tempClientId = (tempClientIdBytes[0] << 8) + tempClientIdBytes[1]; if (!RegisteredClient.ContainsKey(tempClientId)) { clientModel.ClientId = tempClientId; clientId = tempClientId; //注册客户端 RegisteredClient.Add(tempClientId, new List <ClientIDAppID>()); break; } } } } else { clientModel.ClientId = clientId; } lock (_lockObject2) { //循环获取appid,appid是元素下标+1 int maxAppCount = RegisteredClient[clientId].Count; //增加请求的客户端 int[] ports = NetworkUtil.FindAvailableTCPPorts(20000, appCount); foreach (var oneport in ports) { Console.Write(oneport + " "); } Console.WriteLine(" <=端口已分配。"); clientModel.AppList = new List <App>(appCount); for (int i = 0; i < appCount; i++) { int arrangedAppid = maxAppCount + i + 1; if (arrangedAppid > 255) { throw new Exception("Stack overflow."); } //获取可用端口,增加到tcpclient RegisteredClient[clientId].Add(new ClientIDAppID { ClientID = clientId, AppID = arrangedAppid }); clientModel.AppList.Add(new App { AppId = arrangedAppid, Port = ports[i] }); PortAppMap[ports[i]] = new ClientIDAppID { ClientID = clientId, AppID = arrangedAppid }; } } return(clientModel.ToBytes()); }