@@ -164,6 +164,20 @@ function validateBlockSize(size: number): boolean {
164164 return true ;
165165}
166166
167+ // Since coaps:// urls are parsed by the url package, the contained hostname is normalized.
168+ // This function applies the same transformation to any given hostname. Fixes the issue mentioned in #30
169+ /**
170+ * Normalizes a hostname so it matches between `setSecurityParameters` and `connect`
171+ * @param hostname The hostname to normalize
172+ */
173+ function normalizeHostname ( hostname : string ) : string {
174+ // make sure noone gave us a full URI
175+ if ( ! hostname . startsWith ( "coap://" ) && ! hostname . startsWith ( "coaps://" ) ) {
176+ hostname = `coaps://${ hostname } ` ;
177+ }
178+ return nodeUrl . parse ( hostname ) . hostname ;
179+ }
180+
167181/**
168182 * provides methods to access CoAP server resources
169183 */
@@ -192,6 +206,7 @@ export class CoapClient {
192206 * Sets the security params to be used for the given hostname
193207 */
194208 public static setSecurityParams ( hostname : string , params : SecurityParameters ) {
209+ hostname = normalizeHostname ( hostname ) ;
195210 CoapClient . dtlsParams . set ( hostname , params ) ;
196211 }
197212
@@ -1041,8 +1056,9 @@ export class CoapClient {
10411056 /**
10421057 * Establishes a new or retrieves an existing connection to the given origin
10431058 * @param origin - The other party
1059+ * @internal
10441060 */
1045- private static getConnection ( origin : Origin ) : Promise < ConnectionInfo > {
1061+ public static getConnection ( origin : Origin ) : Promise < ConnectionInfo > {
10461062 const originString = origin . toString ( ) ;
10471063 if ( CoapClient . connections . has ( originString ) ) {
10481064 debug ( `getConnection(${ originString } ) => found existing connection` ) ;
@@ -1127,8 +1143,6 @@ export class CoapClient {
11271143 // simply return a normal udp socket
11281144 return Promise . resolve ( new SocketWrapper ( dgram . createSocket ( "udp4" ) ) ) ;
11291145 case "coaps:" :
1130- // return a promise we resolve as soon as the connection is secured
1131- const ret = createDeferredPromise < SocketWrapper > ( ) ;
11321146 // try to find security parameters
11331147 if ( ! CoapClient . dtlsParams . has ( origin . hostname ) ) {
11341148 return Promise . reject ( new Error ( `No security parameters given for the resource at ${ origin . toString ( ) } ` ) ) ;
@@ -1141,6 +1155,10 @@ export class CoapClient {
11411155 } as dtls . Options ) ,
11421156 CoapClient . dtlsParams . get ( origin . hostname ) ,
11431157 ) ;
1158+
1159+ // return a promise we resolve as soon as the connection is secured
1160+ const ret = createDeferredPromise < SocketWrapper > ( ) ;
1161+
11441162 // try connecting
11451163 const onConnection = ( ) => {
11461164 debug ( "successfully created socket for origin " + origin . toString ( ) ) ;
0 commit comments