private void ConnectCallback(IAsyncResult ar) { try { Socket tClient = (Socket)ar.AsyncState; stateObj.workSocket = tClient; BSONObject request = new BSONObject(); request["msg"] = "auth"; request["note"] = "(none)"; request["mID"] = HardwareID.GetHwid(); byte[] requestData = SimpleBSON.Dump(request); tClient.BeginSend(requestData, 0, requestData.Length, SocketFlags.None, new AsyncCallback(SendCallback), stateObj); tClient.BeginReceive(stateObj.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), stateObj); } catch { } }
private void readSocket() { //Console.WriteLine(" - Try to read!"); if (!socket_ready) { return; } if (net_stream.DataAvailable && net_stream.CanRead) { //Debug.Log("Read Socket"); try { // decrypt ? BSONObject obj = null; obj = SimpleBSON.Load(ByteStreamParser.parseStream(net_stream)); IClientCmd clientCmd = cmdMgr.decodeBSON(obj); if (clientCmd != null) { this.observer.addClientCmd(clientCmd); } else { Debug.LogError("ClientCmd not parsed !"); } } catch (Exception e) { Debug.LogError("Exception:" + e); } } }
public void ReadSingleObject() { byte[] data = MiscellaneousUtils.HexToBytes("0F-00-00-00-10-42-6C-61-68-00-01-00-00-00-00"); BSONObject obj = SimpleBSON.Load(data); Assert.AreEqual(obj ["Blah"].int32Value, 1); }
private void writeSocket() { if (!socket_ready) { return; } Queue <IServerCmd> srvCmdList = this.cmdMgr.getServerCmds(); if (srvCmdList.Count <= 0) { return; } //Debug.Log("Write Socket"); for (var i = 0; i < srvCmdList.Count; i++) { IServerCmd cmd = srvCmdList.Dequeue(); BSONObject obj = cmd.encode(); byte[] raw = SimpleBSON.Dump(obj); socket_writer.Write(raw, 0, raw.Length); socket_writer.Flush(); //Debug.Log (" - Command written!"); } }
public void WriteSingleObject() { BSONObject obj = new BSONObject(); obj ["Blah"] = 1; string bson = MiscellaneousUtils.BytesToHex(SimpleBSON.Dump(obj)); Assert.AreEqual("0F-00-00-00-10-42-6C-61-68-00-01-00-00-00-00", bson); }
public void ReadArray() { byte[] data = MiscellaneousUtils.HexToBytes("31-00-00-00-04-42-53-4f-4e-00-26-00-00-00-02-30-00-08-00-00-00-61-77-65-73-6f-6d-65-00-01-31-00-33-33-33-33-33-33-14-40-10-32-00-c2-07-00-00-00-00"); BSONObject obj = SimpleBSON.Load(data); Assert.IsTrue(obj ["BSON"] is BSONArray); Assert.AreEqual(obj ["BSON"][0].stringValue, "awesome"); Assert.AreEqual(obj ["BSON"][1].doubleValue, 5.05); Assert.AreEqual(obj ["BSON"][2].int32Value, 1986); }
private static UpdateInfo ReadInfo() { int XOR_CYPHER = IonConsts.XOR[(int)Consts.ProductID]; var bson = SimpleBSON.Load(File.ReadAllBytes(PathUpdateInfo)); UpdateInfo upinfo = new UpdateInfo() { v = bson["v"].int32Value ^ XOR_CYPHER, // last version n = bson["n"].int32Value ^ XOR_CYPHER, // NTP //r = bson["r"].int32Value^ XOR_CYPHER,// last update date }; return(upinfo); }
public void WriteArray() { byte[] data = MiscellaneousUtils.HexToBytes("31-00-00-00-04-42-53-4f-4e-00-26-00-00-00-02-30-00-08-00-00-00-61-77-65-73-6f-6d-65-00-01-31-00-33-33-33-33-33-33-14-40-10-32-00-c2-07-00-00-00-00"); BSONObject obj = new BSONObject(); obj ["BSON"] = new BSONArray(); obj ["BSON"].Add("awesome"); obj ["BSON"].Add(5.05); obj ["BSON"].Add(1986); byte[] target = SimpleBSON.Dump(obj); Assert.IsTrue(MiscellaneousUtils.ByteArrayCompare(target, data) == 0); }
private byte[] CreateServerStatusMessagePayload(MongoConnectionStringBuilder connectionStringBuilder) { byte[] message; int commandLength; //Write the message first because we need the it's length using (var commandMemoryStream = new MemoryStream()) using (var commandWriter = new BinaryWriter(commandMemoryStream, new UTF8Encoding(), true)) { //Query options commandWriter.Write(0); //Collection name commandWriter.Write($"{connectionStringBuilder.Database}.$cmd".ToArray()); //cstring's require a \x00 at the end. commandWriter.Write('\x00'); //Number to skip commandWriter.Write(0); //Number to return commandWriter.Write(-1); var commandBSON = new BSONObject { ["serverStatus"] = 1.0 }; commandWriter.Write(SimpleBSON.Dump(commandBSON)); commandWriter.Flush(); commandLength = (int)commandMemoryStream.Length; message = new byte[16 + commandLength]; Array.Copy(commandMemoryStream.ToArray(), 0, message, 16, commandLength); } using (var messageMemoryStream = new MemoryStream(message)) using (var completeMessageWriter = new BinaryWriter(messageMemoryStream, new UTF8Encoding(), true)) { //Message length completeMessageWriter.Write(16 + commandLength); //Request Id completeMessageWriter.Write(0); //Response To completeMessageWriter.Write(0); //Operation Code completeMessageWriter.Write(2004); completeMessageWriter.Flush(); } return(message); }
private void sendchatmsg_Click(object sender, EventArgs e) { try { BSONObject request = new BSONObject(); request["msg"] = "chat_req"; request["note"] = chatbox.Text; byte[] requestData = SimpleBSON.Dump(request); stateObj.workSocket.BeginSend(requestData, 0, requestData.Length, SocketFlags.None, new AsyncCallback(SendCallback), stateObj); chatbox.Text = ""; } catch { } }
private byte[] OnPacket(byte[] revBuffer, String from) { // Remove padding and load the bson. byte[] data = new byte[revBuffer.Length - 4]; Buffer.BlockCopy(revBuffer, 4, data, 0, data.Length); BSONObject packets = null; try { packets = SimpleBSON.Load(data); }catch { } if (packets == null || !packets.ContainsKey("mc")) { return(revBuffer); } // Modify the packet? Console.WriteLine(from + " ========================================================================================"); for (int i = 0; i < packets["mc"]; i++) { BSONObject packet = packets["m" + i] as BSONObject; ReadBSON(packet); if (packet["ID"].stringValue == "OoIP") { PIXEL_IP = (packet["IP"].stringValue == "prod.gamev70.portalworldsgame.com" ? "3.220.252.91" : packet["IP"].stringValue); packet["IP"] = "prod.gamev70.portalworldsgame.com"; } } // Dump the BSON and add padding. MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream)) { byte[] bsonDump = SimpleBSON.Dump(packets); binaryWriter.Write(bsonDump.Length + 4); binaryWriter.Write(bsonDump); } return(memoryStream.ToArray()); }
private void getUsersOnline_Tick(object sender, EventArgs e) { try { if (chatbox.Text.Length <= 0) { return; } BSONObject request = new BSONObject(); request["msg"] = "get_online"; request["note"] = "(none)"; byte[] requestData = SimpleBSON.Dump(request); tClient.Client.BeginSend(requestData, 0, requestData.Length, SocketFlags.None, new AsyncCallback(SendCallback), stateObj); } catch { } }
public void ReadBSON(BSONObject SinglePacket, string Parent = "") { foreach (string Key in SinglePacket.Keys) { try { BSONValue Packet = SinglePacket[Key]; switch (Packet.valueType) { case BSONValue.ValueType.String: Console.WriteLine($"{Parent} = {Key} | {Packet.valueType} = {Packet.stringValue}"); break; case BSONValue.ValueType.Boolean: Console.WriteLine($"{Parent} = {Key} | {Packet.valueType} = {Packet.boolValue}"); break; case BSONValue.ValueType.Int32: Console.WriteLine($"{Parent} = {Key} | {Packet.valueType} = {Packet.int32Value}"); break; case BSONValue.ValueType.Int64: Console.WriteLine($"{Parent} = {Key} | {Packet.valueType} = {Packet.int64Value}"); break; case BSONValue.ValueType.Binary: // BSONObject Console.WriteLine($"{Parent} = {Key} | {Packet.valueType}"); ReadBSON(SimpleBSON.Load(Packet.binaryValue), Key); break; case BSONValue.ValueType.Double: Console.WriteLine($"{Parent} = {Key} | {Packet.valueType} = {Packet.doubleValue}"); break; default: Console.WriteLine($"{Parent} = {Key} = {Packet.valueType}"); break; } } catch { } } }
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { // deinitialization might be required here, decide for your self, I get weird service failure errors due to that, too lazy to fix. srvRunning = false; clientRunning = false; try { BSONObject bObj = new BSONObject(); bObj["msg"] = "quit"; bObj["note"] = "Goodbye."; byte[] data = SimpleBSON.Dump(bObj); tClient.Client.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), stateObj.workSocket); } catch { } Environment.Exit(0); }
private static BSONObject ExtractServerStatusFromResponse(TcpClient client) { using (var binaryReader = new BinaryReader(client.GetStream(), new UTF8Encoding(), true)) { //We don't care about the message length and DB RequestId, skip 2 int32's. binaryReader.ReadBytes(8); //Response To int responseTo = binaryReader.ReadInt32(); if (responseTo != 0) { throw new NAMEException($"{SupportedDependencies.MongoDb}: The server responed with an unexpected response code ({responseTo}).", NAMEStatusLevel.Error); } //Op Code int opCode = binaryReader.ReadInt32(); if (opCode != 1) { throw new NAMEException($"{SupportedDependencies.MongoDb}: The server responed with an unexpected operation code ({opCode}).", NAMEStatusLevel.Error); } //We don't care about responseFlags, cursorID or startingFrom. Skip them. binaryReader.ReadBytes(4 + 8 + 4); //Number of documents var numberOfDocuments = binaryReader.ReadInt32(); if (numberOfDocuments != 1) { throw new NAMEException($"{SupportedDependencies.MongoDb}: The server responded with an unexpected number of documents ({numberOfDocuments}).", NAMEStatusLevel.Error); } //The ServerStatus document int size = binaryReader.ReadInt32(); byte[] buffer = new byte[size]; BitConverter.GetBytes(size).CopyTo(buffer, 0); binaryReader.Read(buffer, 4, size - 4); BSONObject obj = SimpleBSON.Load(buffer); return(obj); } }
public void WriteAndRead() { var obj = new BSONObject(); obj["hello"] = 123; obj["where"] = new BSONObject(); obj["where"]["Korea"] = "Asia"; obj["where"]["USA"] = "America"; obj["bytes"] = new byte[41223]; byte [] buf = SimpleBSON.Dump(obj); Console.WriteLine(buf); obj = SimpleBSON.Load(buf); Console.WriteLine(obj["hello"].int32Value); // => 123 Console.WriteLine(obj["where"]["Korea"].stringValue); // => "Asia" Console.WriteLine(obj["where"]["USA"].stringValue); // => "America" Console.WriteLine(obj["bytes"].binaryValue.Length); // => 128-length bytesbytes }
private void ReceiveCallback(IAsyncResult ar) { try { // Retrieve the state object and the client socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket client = state.workSocket; // Read data from the remote device. int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { if (bytesRead < 1024) { byte[] data = new byte[bytesRead]; Array.Copy(state.buffer, data, bytesRead); BSONObject bObj = SimpleBSON.Load(data); string message = bObj["msg"].stringValue; string note = bObj["note"].stringValue; switch (message) { case "auth": { int authState = bObj["auth_state"].int32Value; userInfo.username = bObj["username"].stringValue; if (authState == 0) { MessageBox.Show(note, "Growbrew Server"); } else { //Environment.Exit(authState); } break; } case "get_online": { int count = bObj["c"]; UpdateUserCount(count); break; } case "chat_res": { AppendChat(note); break; } default: break; } } tClient.Client.BeginReceive(stateObj.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), stateObj); } } catch { } }