public async Task <TcpClient> GetClient(int consumerPort) { //从字典的list中取出tcpclient,并将其移除 ClientIDAppID clientappid = PortAppMap[consumerPort].ClientIdAppId; TcpClient client = await AppTcpClientMap[clientappid].ReceiveAsync(); PortAppMap[consumerPort].ReverseClients.Add(client); // AppTcpClientMap[clientappid].Remove(client); //AppRemoved(this, new AppChangedEventArgs { App = clientappid }); return(client); }
public TcpClient GetClient(int consumerPort) { //从字典的list中取出tcpclient,并将其移除 ClientIDAppID clientappid = PortAppMap[consumerPort]; TcpClient client = AppTcpClientMap[clientappid][0]; AppTcpClientMap[clientappid].Remove(client); AppRemoved(this, new AppChangedEventArgs { App = clientappid }); return(client); }
public async Task <TcpClient> GetClient(int consumerPort) { //从字典的list中取出tcpclient,并将其移除 ClientIDAppID clientappid = PortAppMap[consumerPort]; //有时候会取不到 //while (AppTcpClientMap[clientappid].Count == 0) //{ // Task.Delay(1); //} TcpClient client = await AppTcpClientMap[clientappid].ReceiveAsync(); // AppTcpClientMap[clientappid].Remove(client); //AppRemoved(this, new AppChangedEventArgs { App = clientappid }); return(client); }
//通过客户端的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()); }