简体   繁体   English

您如何正确构造和使用套接字缓冲区?

[英]How do you correctly construct and use a buffer for a socket?

I'm trying to convert a piece of code to TypeScript and I've run into an issue with a Buffer that I use with a UDP socket. 我正在尝试将一段代码转换为TypeScript,并且遇到了与UDP套接字一起使用的Buffer的问题。

The code I'm working with looks like this: 我正在使用的代码如下所示:

/// <reference path="../node_modules/DefinitelyTyped/node/node.d.ts" />
import dgram = require( "dgram" );

var udpServer:dgram.Socket = dgram.createSocket( "udp4" );

var message = new Buffer( "foo" );
udpServer.send( message, 0, message.length, 1337, "255.255.255.255" );

WebStorm complains about message with the error Argument type Buffer is not assignable to argument type NodeBuffer . WebStorm抱怨message错误,指出Argument type Buffer is not assignable to argument type NodeBuffer

I understand that this is due to the fact that Socket.send() requires a NodeBuffer as the first argument and I'm supplying a Buffer . 我了解这是由于NodeBuffer Socket.send()需要NodeBuffer作为第一个参数,而我正在提供Buffer的事实。 But how can I overcome this? 但是我该如何克服呢?

I can't use NodeBuffer as the type of message , that just leads to different errors. 我不能使用NodeBuffer作为message的类型,这只会导致不同的错误。

var message:NodeBuffer = new Buffer( "foo" );

Will lead to Initializer type Buffer is not assignable to variable type NodeBuffer 会导致Initializer type Buffer is not assignable to variable type NodeBuffer

var message:NodeBuffer = new NodeBuffer( "foo" );

Will lead to Argument types do not match parameters . 会导致Argument types do not match parameters

This is confusing me due to the examples given at http://nodejs.org/api/dgram.html which worked for me in plain JavaScript. 由于http://nodejs.org/api/dgram.html上提供的示例在纯JavaScript中为我工作,这使我感到困惑。

So, how do I properly construct a buffer that I can send over my UDP socket? 那么,如何正确构造一个可以通过UDP套接字发送的缓冲区?

The problem was caused by having the Node.js v0.8.16 Core Modules library enabled in the JavaScript settings of WebStorm. 该问题是由于在WebStorm的JavaScript设置中启用了Node.js v0.8.16核心模块库引起的。

This confused WebStorm in regards to which type the Buffer actually is. WebStorm对于Buffer实际类型感到困惑。 Disabling the library would resolve the error hint. 禁用该库将解决错误提示。

Sadly, that isn't really an option for us as the project uses both Node.js with JavaScript and TypeScript code. 可悲的是,对于我们来说,这并不是真正的选择,因为该项目同时使用带有JavaScript TypeScript代码的Node.js。 But at least I now know what the problem is. 但是至少我现在知道了问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM