This time I will bring you a summary of the methods of operating binary data in js. What are the precautions for operating binary data in js? Here are practical cases, let’s take a look.
I have recently done several projects, using js to manipulate binary data and transmit it through sockets and the background. Use a blog to record thisFirst create a new socket:
var socket=new WebSocket("ws://192.168.0.147");Then define the function to be executed after the socket is opened and connected: Websocket has an attribute binaryType, which can be set to "blob" or "arraybuffer". The default format is "blob". I forgot to set it to "arraybuffer" when I was working on the project. As a result, I need to use the Blob object when receiving data below. To pick.
socket.onopen=function(){ //发送登录帧,4-20位为手机号 var loginArr=[0X02,0X02,0X00,0X1E,0X20,0X20,0X20,0X20,0X20,0X20,0X20,0X20,0X20,0X20,0X20,0X20,0X20,0X20,0X20,0X20,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X0D,0X0A] }
The following is converted to bypass and sent:
var loginBuffer=new ArrayBuffer(30); var loginDataview=new DataView(loginBuffer); //localstorageuserinfo为缓存在本地的用户手机号 var telArr=localstorageuserinfo.TelPhone; var loginTime=tempTrans(); for(var i=0;i<loginarr.length>3&&i19&&i<loginarr.length-2 socket.send function>=0;i--){ uint8.push(u32Dataview.getUint8(i)) } uint8.push(new DataView(new Uint8Array([time.getMonth()+1]).buffer).getUint8(0)); uint8.push(new DataView(new Uint8Array([time.getDate()]).buffer).getUint8(0)); uint8.push(new DataView(new Uint8Array([time.getHours()]).buffer).getUint8(0)); uint8.push(new DataView(new Uint8Array([time.getMinutes()]).buffer).getUint8(0)); uint8.push(new DataView(new Uint8Array([time.getSeconds()]).buffer).getUint8(0)); return uint8; }</loginarr.length-2></loginarr.length>The sending process is roughly like this. First, create a new ArrayBuffer object. The buffer length parameter needs to be filled in for this object. For details, see api==>
https://msdn.microsoft.com/zh-cn/library /br212474(v=vs.94).aspx,
Then create a new DataView object and pass the ArrayBuffer into it. Then use DataView's setUint and getUint methods to read and set bits. For details, refer to api==> https://msdn.microsoft.com/zh-cn/library/br212463(v=vs.94).aspxThe following is the processing of receiving data:
//接收消息onmessage socket.onmessage=function(data){ var blob_=new Blob([data.data]); parseBlob(blob_); } //使用fileReader操作blob对象 var reader = { readAs: function(type,blob,cb){ var r = new FileReader(); r.onloadend = function(){ if(typeof(cb) === 'function') { cb.call(r,r.result); } } try{ r['readAs'+type](blob); }catch(e){} } } function parseBlob(blob){ reader.readAs('ArrayBuffer',blob.slice(0,blob.size),function(arr){ var dataview_=new DataView(arr); //协议中第二位是判断数据来源的 var socketConType=dataview_.getUint8(1); //转成字符串读取数据 var modulelength=(dataview_.buffer.byteLength-46)/33; var modulestate={}; reader.readAs('Text',blob.slice(i*33+37,i*33+37+32),function(result){ modulestate[dataview_.getUint8(i*33+36)]=result; }); }) }After converting it to a string, you can do whatever you want. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
What are the techniques for Vue component development
The above is the detailed content of Summary of js methods for operating binary data. For more information, please follow other related articles on the PHP Chinese website!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment