public static void ChangeMap(int type, Map map) { try { map.ChangeType = type; ChangeMapList(map); var natClient = NATServer.GetSingle(c => c.Client?.id == map.client_id); if (natClient == null) { return; } ChangeMap(map, natClient); var pack = PackHelper.CreatePack(new JsonData() { Type = (int)JsonType.NAT, Action = (int)NatAction.MapChange, Data = map.ToJson() }); natClient.Send(pack); } catch (Exception ex) { HandleLog.WriteLine($"映射更新异常:{ex},参数为:{JsonHelper.Instance.Serialize(map)}"); } }
public PackHelper getManager(string name, string path, Action doneEvent = null, bool isThred = true) { if (path == null || name == null) { return(null); } if (!File.Exists(path)) { return(null); } if (packManager.ContainsKey(name)) { PackHelper pkh = packManager[name]; pkh.ReadTableIsDone = doneEvent; if (pkh.initiated) { if (doneEvent != null) { doneEvent.Invoke(); } } return(pkh); } else { PackHelper pkh = new PackHelper(path, isThred); pkh.progress_bar += dummy; packManager[name] = pkh; pkh.ReadTableIsDone = doneEvent; return(pkh); } }
private void OnPackageReceived(Socket socket, NatPackageInfo packageInfo) { Task.Run(() => { var tcpModel = packageInfo.Raw; //先gzip压缩 再转为16进制字符串 var body = DataHelper.Compress(packageInfo.Raw); var pack = PackHelper.CreatePack(new JsonData() { Type = (int)JsonType.TCP, Action = (int)TcpAction.TransferData, Data = new TcpModel() { ServerId = RemoteSession.ServerId, Host = RemoteSession.Host, Local = RemoteSession.Local, SessionId = RemoteSession.SessionId, Content = body }.ToJson() }); //转发给服务器 NatClient.Send(pack); HandleLog.WriteLine($"<---- {RemoteSession.SessionId} 收到报文{packageInfo.Raw.Length}字节"); }); }
private void pictureBox1_Click(object sender, EventArgs e) { unpacking = false; OpenFileDialog theDialog = new OpenFileDialog(); theDialog.Title = "Open Pck File"; theDialog.Filter = "Pck files|*.Pck"; if (theDialog.ShowDialog() == DialogResult.OK) { string path = theDialog.FileName; if (Path.GetExtension(path) == ".pck") { unppack_path = path; } if (unppack_path.Length <= 1) { JMessageBox.Show(this, "Please select .pck!"); } else { autoOpenPath = unppack_path; autoLoad = true; openedPckFies = new PackHelper(unppack_path, true); openedPckFies.ReadTableIsDone = initialRead; openedPckFies.progress_bar += progress_bar; this.fiullFilePath = unppack_path; } } }
private void AutoOpen() { if (this.InvokeRequired) { this.Invoke(new MethodInvoker(delegate { AutoOpen(); })); return; } if (autoLoad && autoOpenPath.Length > 0 && File.Exists(autoOpenPath)) { string path = autoOpenPath; if (Path.GetExtension(path) == ".pck") { unppack_path = path; } if (unppack_path.Length <= 1) { JMessageBox.Show(this, "Please select .pck!"); } else { if (openedPckFies != null) { openedPckFies.Dispose(); } openedPckFies = new PackHelper(unppack_path, true) { ReadTableIsDone = initialRead }; openedPckFies.progress_bar += progress_bar; this.fiullFilePath = unppack_path; } } }
private bool RecvBytes(Socket tcp) { lock (bufferRecv) { byte[] buffer = bufferRecv; int received = tcp.Receive(buffer); //received = tcp.ReceiveAsync.Receive(buffer); byte[] bytesReceived = PackHelper.DecodeBytes(buffer, 1, received - 2); int rightSize = HeadPack.PackSize + ServerAnswerPack.PackSize + 1; if (bytesReceived.Length != rightSize) { log.WarnFormat("返回消息长度不正确:" + bytesReceived.Length + "!=" + rightSize); } ServerAnswerPack pack = new ServerAnswerPack(); RawFormatter.Instance.Bytes2Struct(pack, bytesReceived, HeadPack.PackSize, ServerAnswerPack.PackSize); if (pack.Result != 0) { log.WarnFormat("发送失败:" + pack.Result.ToString()); } if (waitReceive && receiveLogPrint) { Console.WriteLine("SeqNO:{0} MessageId:{1} Result:{2}", pack.SeqNO, pack.MessageId, pack.Result); } return(pack.Result == 0); } }
private void jPictureBox1_Click(object sender, EventArgs e) { progress_bar("Creating...", 0, 0); RenameForm rf = new RenameForm(); DialogResult res = rf.ShowDialog(this); if (res == DialogResult.OK && RenameForm.value != null && RenameForm.value.Length > 0) { using (var fbd = new FolderBrowserDialog()) { DialogResult result = fbd.ShowDialog(); if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) { string path = Path.Combine(fbd.SelectedPath, Path.GetFileNameWithoutExtension(RenameForm.value) + ".pck"); File.WriteAllBytes(path, Resources.BlankPk); if (Path.GetExtension(path) == ".pck") { unppack_path = path; } if (unppack_path.Length <= 1) { JMessageBox.Show(this, "Please select .pck!"); } else { openedPckFies = new PackHelper(unppack_path, true); openedPckFies.ReadTableIsDone = initialRead; openedPckFies.progress_bar += progress_bar; this.fiullFilePath = unppack_path; } } } } progress_bar("Ready", 0, 0); }
public bool ExtractSfx() { try { string sfx = Directory.GetParent(Path.GetDirectoryName(ElementEditorPath)).FullName + Path.DirectorySeparatorChar + "sfx.pck"; PackHelper gfxManager = getManager("sfx.pck", sfx, null, false, false); if (gfxManager == null) { return(true); } foreach (string str in this.sfx) { List <PckEntry> dd = gfxManager.getDirectory(Path.GetDirectoryName(str), true, Path.GetFileName(str)); for (int i = 0; i < dd.Count; i++) { PckEntry curGfx = dd[i]; string dirpath = Path.GetDirectoryName(Path.Combine(saveDirectory, curGfx.fullP)); string subpath = Path.Combine(saveDirectory, curGfx.fullP); string fileEx = Path.GetExtension(subpath).Replace(".", "").ToLower(); if (!Directory.Exists(dirpath)) { Directory.CreateDirectory(dirpath); } File.WriteAllBytes(subpath, curGfx.bytes); } } } catch { } return(true); }
private void Received(TcpSession session, NatRequestInfo requestInfo) { Task.Run(() => { try { while (session.NatSession == null) { Thread.Sleep(50); } //先gzip压缩 再转为16进制字符串 var body = DataHelper.Compress(requestInfo.Raw); //转发数据 var pack = new JsonData() { Type = (int)JsonType.TCP, Action = (int)TcpAction.TransferData, Data = new TcpModel() { ServerId = ServerId, Host = session.Map?.remote_endpoint, Local = session.Map?.local_endpoint, SessionId = session.SessionId, Content = body }.ToJson() }; session.NatSession.Send(PackHelper.CreatePack(pack)); HandleLog.WriteLine($"<---- {session.SessionId} 收到报文{body.Length}字节"); } catch (Exception ex) { HandleLog.WriteLine($"【{session.Local}】请求参数:{requestInfo.Raw.ToHexWithSpace()},处理发生异常:{ex}"); } }); }
public void ShuffleAndDeal() { var pack = PackHelper.BuildPiquetPack(); var shuffledPack = PackHelper.Shuffle(pack); foreach (var player in Players) { CardsHeldByPlayers[player] = new List <Card>(); CardsHeldByPlayers[player].Add(shuffledPack.Pop()); CardsHeldByPlayers[player].Add(shuffledPack.Pop()); CardsHeldByPlayers[player].Add(shuffledPack.Pop()); CardsPlayedByPlayers[player] = new List <Card>(); } foreach (var player in Players) { CardsHeldByPlayers[player].Add(shuffledPack.Pop()); CardsHeldByPlayers[player].Add(shuffledPack.Pop()); } foreach (var player in Players) { CardsHeldByPlayers[player].Add(shuffledPack.Pop()); CardsHeldByPlayers[player].Add(shuffledPack.Pop()); CardsHeldByPlayers[player].Add(shuffledPack.Pop()); } }
public void Int32_ToBytes_ReturnsExpectedValue(int input, int expectedResult) { // Act var result = PackHelper.Int32(input); // Assert result.Should().ContainInOrder(BitConverter.GetBytes(expectedResult)); }
public void UInt64_ToBytes_ReturnsExpectedValue(ulong input, ulong expectedResult) { // Act var result = PackHelper.UInt64(input); // Assert result.Should().ContainInOrder(BitConverter.GetBytes(expectedResult)); }
private bool SendPosition(Socket tcp) { HeadPack head = new HeadPack() { SeqNO = GetNextSeqNum(), MessageId = (ushort)MessageIds.PositionReport, BodyProp = (ushort)0 }; head.SetDeviceId(this.deviceId); double lat; double lon; int speed = 10 + r.Next(90); latlonBuilder.GetNextLatlon(speed, out lat, out lon); PositionReportPack pack = new PositionReportPack() { AlermFlags = 0, Speed = (ushort)(speed * 10), State = 0, Latitude = Convert.ToUInt32(lat * 1000000), Longitude = Convert.ToUInt32(lon * 1000000), Altitude = 200, Direction = 0, Time = DateTime.Now.ToString("yyMMddHHmmss") }; byte[] bytesSend = RawFormatter.Instance.Struct2Bytes(pack); BodyPropertyHelper.SetMessageLength(ref head.BodyProp, (ushort)bytesSend.Length); byte[] headBytes = RawFormatter.Instance.Struct2Bytes(head); byte[] fullBytes = headBytes.Concat(bytesSend).ToArray(); byte checkByte = PackHelper.CalcCheckByte(fullBytes, 0, fullBytes.Length); bytesSend = (new byte[] { 0x7e } .Concat(PackHelper.EncodeBytes(fullBytes.Concat(new byte[] { checkByte }))) .Concat(new byte[] { 0x7e })).ToArray(); //Console.WriteLine("{0} {1}",head.SeqNO, bytesSend.ToHexString()); //发送消息 SendBytes(tcp, bytesSend); //控制台打印日志cpu占用太高 if (sendLogPrint) { Console.WriteLine("{0} {1}, LatLon:{2:0.000000},{3:0.000000}", head.GetDeviceId(), DateTime.Now.ToString(), lat, lon); } //等待接收服务端返回值 var success = true; if (waitReceive) { success = RecvBytes(tcp); //var success = true; } return(success); }
public void BuildPiquetPackTest() { var piquetPack = PackHelper.BuildPiquetPack(); Assert.AreEqual(32, piquetPack.GetCardsCount()); var allCards = piquetPack.ToString(); Assert.AreEqual("7♠|7♥|7♦|7♣|8♠|8♥|8♦|8♣|9♠|9♥|9♦|9♣|10♠|10♥|10♦|10♣|J♠|J♥|J♦|J♣|Q♠|Q♥|Q♦|Q♣|K♠|K♥|K♦|K♣|A♠|" + "A♥|A♦|A♣", allCards); }
public void ShufflePackTest() { var piquetPack = PackHelper.BuildPiquetPack(); var shuffledPack = PackHelper.Shuffle(piquetPack); Assert.AreEqual(32, shuffledPack.GetCardsCount()); Assert.AreNotEqual(piquetPack.ToString(), shuffledPack.ToString()); var shuffledAgainPack = PackHelper.Shuffle(shuffledPack); Assert.AreNotEqual(shuffledPack.ToString(), shuffledAgainPack.ToString()); }
static void OnClientConnected(Socket socket) { //发送注册包给服务端 var pack = PackHelper.CreatePack(new JsonData() { Type = (int)JsonType.NAT, Action = (int)NatAction.Connect, Data = Secret }); NatClient?.Send(pack); }
public RPC_HELO(byte[] buffer1) { var buffer = Unpooled.WrappedBuffer(buffer1); protocole = (uint)PackHelper.packdd(buffer); var length = PackHelper.packdd(buffer); hexrays_licence = buffer.ReadString(length, Encoding.UTF8); hexrays_id = buffer.ReadUnsignedInt(); watermak = buffer.ReadUnsignedShort(); field_0x36 = (uint)PackHelper.packdd(buffer); }
public void SendServerMessage(NatSession session, ServerMessage serverMessage) { HandleLog.WriteLine(serverMessage.Message); var pack = new JsonData() { Type = (int)JsonType.NAT, Action = (int)NatAction.ServerMessage, Data = serverMessage.ToJson() }; //转发给客户端 session?.Send(PackHelper.CreatePack(pack)); }
public byte[] Message() { byte[] messageBytes = new byte[this.PacketLength]; byte[] lengthBytes = PackHelper.UInt32(this.MessageLength); lengthBytes.CopyTo(messageBytes, 0); messageBytes[4] = this.MessageID; this.MessagePayload.CopyTo(messageBytes, 5); return(messageBytes); }
private void DoWork() { try { mainPackName = FileToRip.Split(Path.DirectorySeparatorChar)[0] + ".pck"; string packPath = Directory.GetParent(Path.GetDirectoryName(ElementEditorPath)).FullName + Path.DirectorySeparatorChar + mainPackName; PackHelper man = getManager(mainPackName, packPath, FinishExtractingMainFile, true); if (man == null) { AllDone(); } } catch { AllDone(); } }
private PackHelper getManager(string name, string path, Action doneEvent = null, bool hasProgress = false, bool isThread = true) { PackHelper tpackManager = PackDatabase.Instance.getManager(name, path, doneEvent, isThread); if (tpackManager != null) { if (hasProgress) { tpackManager.progress_bar += progress_bar; } tpackManager.ReadTableIsDone = doneEvent; } return(tpackManager); }
public void CreateNewDatabase(string ElementEditorPath, int version) { _NAME = ElementEditorPath.ToLower(); string surfacespck = Directory.GetParent(Path.GetDirectoryName(ElementEditorPath)).FullName + Path.DirectorySeparatorChar + "surfaces.pck"; string configspck = Directory.GetParent(Path.GetDirectoryName(ElementEditorPath)).FullName + Path.DirectorySeparatorChar + "configs.pck"; string world_targets = Directory.GetParent(Path.GetDirectoryName(ElementEditorPath)).FullName + Path.DirectorySeparatorChar + "maps" + Path.DirectorySeparatorChar + "world" + Path.DirectorySeparatorChar + "world_targets.txt"; //GET FILES if (!File.Exists(surfacespck)) { PackDatabase.Instance.Clear(); return; } if (!File.Exists(configspck)) { PackDatabase.Instance.Clear(); return; } if (!File.Exists(world_targets)) { PackDatabase.Instance.Clear(); return; } cts.Cancel(); cts = new CancellationTokenSource(); ct = cts.Token; PackDatabase.Instance.Clear(); CURRENT_SESSION.Clear(); CURRENT_SESSION = null; GC.Collect(); CURRENT_SESSION = new Session(); CURRENT_SESSION.Version = version; CURRENT_SESSION.isredyC1 = CURRENT_SESSION.isredyC2 = CURRENT_SESSION.hasJustBecomeReady = false; configspckManager = PackDatabase.Instance.getManager("configs.pck", configspck, configsLoaded, true); surfacespckManager = PackDatabase.Instance.getManager("surfaces.pck", surfacespck, SurfacesLoaded, true); Task <bool>[] taskList = { Task.Factory.StartNew(() => LoadAddonList(_NAME), ct), //LOAD FROM DEFAULT Task.Factory.StartNew(() => LoadLocalizationText(_NAME), ct), //LOAD FROM DEFAULT Task.Factory.StartNew(() => LoadInstanceList(_NAME), ct), //LOAD FROM DEFAULT Task.Factory.StartNew(() => LoadRelayStationList(_NAME, new MemoryStream(File.ReadAllBytes(world_targets))),ct), Task.Factory.StartNew(() => loadItemList(_NAME), ct) //item_list_index.txt }; Task.WaitAll(taskList); }
private void Received(HttpSession session, HttpRequestInfo requestInfo) { try { var httpModel = new HttpModel { RequestTime = DateTime.Now, ServerId = ServerId, SessionId = session.SessionId }; var filter = ReceiveFilter as HttpReceiveFilter; filter.DecodePackage(ref httpModel); //转发请求 var natSession = NATServer.GetSingle(c => c.MapList.Any(c => c.remote_endpoint == httpModel.Host)); if (natSession == null) { //TODO 错误页面 HandleLog.WriteLine($"穿透客户端未连接到服务器,请求地址:{httpModel.Host}{httpModel.Path}"); var response = new HttpResponse() { Status = 404, ContentType = "text/html", Body = Encoding.UTF8.GetBytes("nat client not found") }; //把处理信息返回到客户端 session.Send(response.Write()); } else { //转发数据 var pack = new JsonData() { Type = (int)JsonType.HTTP, Action = (int)HttpAction.Request, Data = httpModel.ToJson() }; natSession.Send(PackHelper.CreatePack(pack)); session.NatSession = natSession; } } catch (Exception ex) { HandleLog.WriteLine($"【{session.Local}】请求地址:{requestInfo.BaseUrl}{requestInfo.Path},处理发生异常:{ex}"); } }
static void SendHeart() { while (IsReConnect) { Thread.Sleep(50000); if (NatClient.IsConnected) { //发送心跳包给服务端 var pack = PackHelper.CreatePack(new JsonData() { Type = (int)JsonType.NAT, Action = (int)NatAction.Heart, Data = Secret }); NatClient?.Send(pack); } } }
public void CloseLocalClient(TcpSession session) { var pack = new JsonData() { Type = (int)JsonType.TCP, Action = (int)TcpAction.Close, Data = new TcpModel() { ServerId = ServerId, Host = session.Map?.remote_endpoint, Local = session.Map?.local_endpoint, SessionId = session.SessionId }.ToJson() }; //转发给客户端 session.NatSession?.Send(PackHelper.CreatePack(pack)); }
private void Connected(TcpSession session) { try { //转发连接请求 var natSession = ServerHanlder.NATServer.GetSingle(c => c.MapList?.Any(m => m.remote_port == ServerOption.Port) ?? false); if (natSession == null) { session?.Close(); HandleLog.WriteLine($"请求:{session.Local}失败,Nat客户端连接不在线!"); return; } var map = natSession.MapList?.Find(c => c.remote_port == ServerOption.Port); if (map == null) { session?.Close(); HandleLog.WriteLine($"请求:{session.Local}失败,映射{session.Local}不存在!"); return; } session.Map = map; //tcp连接注册包 var pack = new JsonData() { Type = (int)JsonType.TCP, Action = (int)TcpAction.Connect, Data = new TcpModel() { ServerId = ServerId, Host = map?.remote_endpoint, Local = map?.local_endpoint, SessionId = session.SessionId }.ToJson() }; natSession.Send(PackHelper.CreatePack(pack)); session.NatSession = natSession; HandleLog.WriteLine($"客户端【{session.SessionId},{session.Remote}】已连接【{session.Local}】"); } catch (Exception ex) { HandleLog.WriteLine($"连接【{session.SessionId},{session.Local}】发生异常:{ex}"); } }
//#region 设置当前答题流程答案 ///// <summary> ///// 设置当前答题流程答案 ///// </summary> ///// <param name="command"></param> ///// <param name="result"></param> //public void SetFlowAnswers(Flows.FlowCommand command, string result) //{ // if (FlowAnswers.ContainsKey(command)) // { // FlowAnswers[command] = result; // } // else // { // FlowAnswers.Add(command, result); // } //} //#endregion #region 向设备发送文本内容 /// <summary> /// 向设备发送文本内容 /// </summary> /// <param name="text"></param> public void SendText(string text, bool isTcp) { if (!isTcp) { var ret = CheckDeviceBind(); if (ret == false) return; } var pack = PackHelper.CreateSend(this.mDeviceId); var datas = pack.SendTextPack(text, isTcp); if (isTcp) { PenController.Instance.PendSend(datas, this.mTcpClient); } else if (this.mIpAddress != null) { PenController.Instance.PendSend(datas, this.mIpAddress); } }
public void SaveTextures(PckEntry entry) { try { string gfx = Directory.GetParent(Path.GetDirectoryName(ElementEditorPath)).FullName + Path.DirectorySeparatorChar + "gfx.pck"; const Int32 BufferSize = 128; using (var streamReader = new StreamReader(new MemoryStream(entry.bytes), Encoding.GetEncoding("GB2312"), true, BufferSize)) { String line; while ((line = streamReader.ReadLine()) != null) { if (line.ToLower().StartsWith("texfile")) { string fileName = line.Split(':')[1].TrimStart(); if (fileName.Length > 3) { PackHelper aa = getManager("gfx.pck", gfx, null); if (aa != null) { List <PckEntry> dd = aa.getDirectory("gfx" + Path.DirectorySeparatorChar + "textures" + Path.DirectorySeparatorChar + Path.GetDirectoryName(fileName), true, Path.GetFileName(fileName)); for (int i = 0; i < dd.Count; i++) { PckEntry curGfx = dd[i]; string dirpath = Path.GetDirectoryName(Path.Combine(saveDirectory, curGfx.fullP)); string subpath = Path.Combine(saveDirectory, curGfx.fullP); string fileEx = Path.GetExtension(subpath).Replace(".", "").ToLower(); if (!Directory.Exists(dirpath)) { Directory.CreateDirectory(dirpath); } File.WriteAllBytes(subpath, curGfx.bytes); } } } } } } } catch { } }
public bool OnHandshake(IPeerWireClient client) { BDict handshakeDict = new BDict(); BDict mDict = new BDict(); byte i = 1; foreach (IBTExtension extension in this._protocolExtensions) { this._extOutgoing.Add(new ClientProtocolIDMap(client, extension.Protocol, i)); mDict.Add(extension.Protocol, new BInt(i)); i++; } handshakeDict.Add("m", mDict); string handshakeEncoded = BencodingUtils.EncodeString(handshakeDict); byte[] handshakeBytes = Encoding.ASCII.GetBytes(handshakeEncoded); Int32 length = 2 + handshakeBytes.Length; client.SendBytes((new byte[0]).Cat(PackHelper.Int32(length).Cat(new[] { (byte)20 }).Cat(new[] { (byte)0 }).Cat(handshakeBytes))); return(true); }
public void RequestMetaData(IPeerWireClient peerWireClient) { byte[] sendBuffer = new byte[0]; for (Int32 i = 0; i < this._pieceCount; i++) { BDict masterBDict = new BDict { { "msg_type", (BInt)0 }, { "piece", (BInt)i } }; string encoded = BencodingUtils.EncodeString(masterBDict); byte[] buffer = PackHelper.Int32(2 + encoded.Length); buffer = buffer.Concat(new byte[] { 20 }).ToArray(); buffer = buffer.Concat(new[] { this._parent.GetOutgoingMessageID(peerWireClient, this) }).ToArray(); buffer = buffer.Concat(Encoding.GetEncoding(1252).GetBytes(encoded)).ToArray(); sendBuffer = sendBuffer.Concat(buffer).ToArray(); } peerWireClient.SendBytes(sendBuffer); }