/// <summary> /// Trong lúc client yêu câu kết nối /// </summary> /// <param name="ar"></param> private void OnConnectRequest(IAsyncResult ar) { Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); if (!_online) { handler.Shutdown(SocketShutdown.Both); handler.Close(); listener.Shutdown(SocketShutdown.Both); listener.Close(); } else try { if (_PlayerList.Count < _iPlayers) { int readBytes = handler.Receive(buffer); if (readBytes > 0) { //Remove all null-byte chars in buffer string Msg = _ENCODE.GetString(buffer).Trim('\0'); cmdMsg cmd = (cmdMsg)Enum.Parse(typeof(cmdMsg), Msg.Substring(0, 4)); if (cmd == cmdMsg.HELO) { PlayerID id = new PlayerID(Msg.Remove(0, 4), _PlayerList.Count); NewConnection(handler, id); } } listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener); } else { handler.Send(_ENCODE.GetBytes("REJ\nServer's full")); //handler.Shutdown(SocketShutdown.Both); //handler.Close(5); } } catch (SocketException socketException) { if (socketException.ErrorCode == 10054 || ((socketException.ErrorCode != 10004) && (socketException.ErrorCode != 10053))) { handler.Close(); } } }
/// <summary> /// hàm khởi tạo pClietn từ socket đang muốn kết nối vào và ID của client /// </summary> /// <param name="client"></param> /// <param name="id"></param> public pClient(Socket client,PlayerID id) { sock = client; _playerID = id; _status = "Connected"; }
/// <summary> /// tạo kết nối mới cho client dc chấp nhận /// </summary> /// <param name="clientSock"></param> /// <param name="id"></param> private void NewConnection(Socket clientSock, PlayerID id) { pClient client = new pClient(clientSock, id); _PlayerList.Add(client); ListViewItem item = new ListViewItem(); ListViewItem.ListViewSubItemCollection subitems = new ListViewItem.ListViewSubItemCollection(item); item.Tag = client; GUI.EditListView(item, subitems); byte[] Helo = _ENCODE.GetBytes("HELO\n" + GUI.timeOutSecond.ToString() + "\n" + GUI._ContainerList.Capacity.ToString() + "\n" + "Connected at: " + DateTime.Now.ToLongTimeString()); client.sock.Send(Helo); client.SetupForRecv(this); }