Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue in setting up a signaling-server: peerjs.min.js?a0bc:52 WebSocket connection failed #193

Open
marcoippolito opened this issue May 26, 2020 · 14 comments

Comments

@marcoippolito
Copy link

marcoippolito commented May 26, 2020

In Ubuntu 18.04.4 Desktop with node v14.3.0,

I made various attempts to setting up a signaling-server, but got errors.

My app is running behind an nginx proxy server.

  • First attempt:

    in Peerjs.vue file:

    data: () => ({
    peerServer: PeerServer({
    port: 9000,
    path: '/ggc',
    }),

    But when I run npm run server I get this error:
    image

  • 2nd attempt:

    I tried to run the signaling server in this simpler way:

    $ peerjs --port 9000 --key peerjs --path /myapp
    Started PeerServer on ::, port: 9000, path: /myapp (v. 0.5.3)
    

    going to the address http://127.0.0.1:9000/myapp

image

    random_id = function  ()  {
      return Math.random().toString(36).replace('0.', '') ;
    }

    data: () => ({
        myPeerId: random_id(),
    }),
    created() {
      //this.myPeer = new Peer()
      console.log("this.myPeerId= ", this.myPeerId);
      this.myPeer = new Peer(this.myPeerId, {
        host: 'localhost',
        port: 9000,
        path: '/myapp'
      })

But I get this error:

  WebSocket connection to 'wss://localhost:9000/myapp/peerjs?key=peerjs&id=1neg9klb0iy&
  token=ijgdzb2nkb' failed: Error in connection establishment: 

net::ERR_SSL_PROTOCOL_ERROR

image

image

3rd attempt:

If I don't specify any id when connecting to the server from the client PeerJS:

      this.myPeer = new Peer({
        host: 'localhost',
        port: 9000,
        path: '/myapp'
      })

I get this other error:

  GET https://localhost:9000/myapp/peerjs/id?ts=15904855372680.20747018518962235   
  net::ERR_SSL_PROTOCOL_ERROR
  peerjs.min.js?a0bc:64 Fetch failed loading: GET "https://localhost:9000/myapp/peerjs
  /id?ts=15904855372680.20747018518962235"

image

4th attempt:

I also tried to run the Peer Signaling Server as follows:

nano peerjs_server.js :

  import pkg from 'peer';
  const { PeerServer } = pkg;

  const peerServer = PeerServer({ port:9000, path: '/myapp' });


  node peerjs_server.js 

But I get this error:

  GET https://localhost:9000/myapp/peerjs/id?ts=15904877618790.4601257822981697 
  net::ERR_SSL_PROTOCOL_ERROR

  peerjs.min.js?a0bc:64 Fetch failed loading: GET "https://localhost:9000/myapp/peerjs
  /id?ts=15904877618790.4601257822981697".

image

5th attempt:

I discovered here: https://flaviocopes.com/peerjs/
that I can run peerjs server using npx:

  $ npx peerjs --port 9000
  Started PeerServer on ::, port: 9000, path: / (v. 0.5.3)

in Peerjs.vue file :

    created() {
      this.myPeer = new Peer('receiver', {
        host: 'localhost',
        port: 9000,
        path: '/'
      })

But got this error:

WebSocket connection to 'wss://localhost:9000/peerjs?key=peerjs&id=receiver&token=jrhkw3ecth'   
failed: Error in connection establishment: net::ERR_SSL_PROTOCOL_ERROR

image

Wha am I doing wrongly?
How to solve the problem?
Looking forward to your kind help.
Marco

@marcoippolito marcoippolito changed the title Issue in setting up a signaling-server Issue in setting up a signaling-server: peerjs.min.js?a0bc:52 WebSocket connection failed May 26, 2020
@Florrr
Copy link

Florrr commented May 26, 2020

ERR_SSL_PROTOCOL_ERROR - if you are using the wss:// socket, you need to provide a ssl certificate.

const peerServer = PeerServer({
  port: 9000,
  ssl: {
    key: fs.readFileSync('/path/to/your/ssl/key/here.key'),
    cert: fs.readFileSync('/path/to/your/ssl/certificate/here.crt')
  }
});

Alternatively, (if you are using localhost), you could set secure parameter to false tu use the ws:// socket without an ssl certificate

this.myPeer = new Peer('receiver', {
        host: 'localhost',
        port: 9000,
        path: '/',
        secure: false
      })

@marcoippolito
Copy link
Author

marcoippolito commented May 26, 2020

Hi @Florrr !

With:

    this.myPeer = new Peer('receiver', {
      host: 'localhost',
      port: 9000,
      path: '/',
      secure: false
    })

I still don't get the connection between the two peers (desktop and mobile phone):

image

Screenshot_20200526-151602

image

@Florrr
Copy link

Florrr commented May 26, 2020

But it seems that the connection to the signaling-server has been established (since there is no error)
Verify, that your signaling server is running: is a json displayed when visiting https.//gcc.world:9000/ on both devices?

Has the connection worked previously with the public peerjs signaling-server?

EDIT:
Btw. I've never used a signaling server located at the same server as the web-server. Therefore I'm not sure whether "localhost" is pointing to the webserver or to the local device.

@marcoippolito
Copy link
Author

marcoippolito commented May 26, 2020

image

The connection worked perfectly fine till yesterday with public peerjs signaling-server.

Yes, now I'm trying to use a signaling server located at the same server as the web-server.
If "localhost" is pointing to the web-server, which I'm not sure about, what kind of problem would pose?
I tried to run the peerjs-server on a laptop connected to the same local network:

   this.myPeer = new Peer('receiver', {
      //host: 'localhost',
      host: '192.168.1.5',
      port: 9000,
      path: '/',
      secure: false
      //ssl: {
      //  key: fs.readFileSync(''),
      //  cert: fs.readFileSynce('')
      //}
    })

image

But I got this error messages:

image

So, I suppose, I should keep trying to locate the signaling server on the same machine of the web-server.

@marcoippolito
Copy link
Author

marcoippolito commented May 26, 2020

@Florrr do I need to explicitly create the Peer also for the mobile part?
Till yesterday, it worked fine without needing to explicitly create the second Peer:

    fromMobileDecode (result) {
      this.remotePeerId = result;
      this.fromMobileConnect();
      this.qrTurnCameraOff();
    },
   fromMobileConnect() {
      this.connection = this.myPeer.connect(this.remotePeerId)
      console.log('Now connected:', this.connection);
      // Receive messages:
      this.connection.on('open', () => {
        this.connection.on('data', newMessage => this.messages.push(newMessage))
      });
    },

But, as far as I understand from here https://flaviocopes.com/peerjs/
I need to explicitly define the second Peer.

    fromMobileDecode (result) {
      this.remotePeerId = result;
      this.fromMobileConnect();
      this.qrTurnCameraOff();
    },
    fromMobileConnect() {
      this.mobilePeer = new Peer({
        host: 'localhost',
        port: 9000,
        path: '/',
        secure: false
      })
      this.connection = this.mobilePeer.connect(this.remotePeerId);
      console.log('Now connected:', this.connection);
      // Receive messages:
      this.connection.on('open', () => {
        this.connection.on('data', newMessage => this.messages.push(newMessage))
      });
    },

What I do not understand is why I see the first peer, the desktop peer, connecting:

image

 npx peerjs --port 9000
Started PeerServer on ::, port: 9000, path: / (v. 0.5.3)
Client connected: 21f784c9-1bd7-4d2b-b1ec-f0b1d564cdf0

But I do not see connecting the second peer, the mobile peer

@Florrr
Copy link

Florrr commented May 26, 2020

When changing the host from localhost to a public ip, you need to specify the ssl keys (see https://github.com/peers/peerjs-server for how to specify the keys. e.g Using the CLI with the options --sslkey and --sslcert)

I'd recommend following this setup guide: https://peerjs.com/docs.html#api
new Peer() creates an object which handles (multiple or only a single) p2p connection - so there is no need to create multiple Peer objects (Only one peer-object per device)
Are you using different ids for each peer-object? I only know about the receiver-ID. Is the id of the mobile device different? The signaling-server might refuse the connection if the ID is already defined.
For debuging consider checking your console output on the mobile device using remote tools https://developers.google.com/web/tools/chrome-devtools/remote-debugging

@marcoippolito
Copy link
Author

marcoippolito commented May 26, 2020

Till now I didn't use any ssl key and ssl cert. This is why I do not understand when you say "changing the host from localhost to a public ip": till yesterday both Peer objects were connected to the public signaling-server. Now that I host my own signaling-server, do I have to specify an ssl key an ssl cert for https ( https://github.com/peers/peerjs-server#using-https )?

Can I use as ssl key and ssl cert the ones I defined for certbot, or do I need to define different ssl cert and key? If they must be different than the ones I already have for certbot, what's the best way to get new ones?

I'm using different ids for each peer-object

Just to understand how the workflow works, I issued self-signed ssl key and cert.

peerjs --port 9000 --sslkey /home/marco/myTempCerts/my.key --sslcert /home/marco/myTempCerts/my.crt
Started PeerServer on ::, port: 9000, path: / (v. 0.5.3)

image

and specified the path to key and crt within both peer objects:

    this.myPeer = new Peer({
      host: 'localhost',
      port: 9000,
      path: '/',
      //secure: false
      ssl: {
        key: fs.readFileSync('/home/marco/myTempCerts/my.key'),
        cert: fs.readFileSync('/home/marco/myTempCerts/my.crt')
      }
    })


      this.mobilePeer = new Peer({
        host: 'localhost',
        port: 9000,
        path: '/',
        //secure: false
        ssl: {
          key: fs.readFileSync('/home/marco/myTempCerts/my.key'),
          cert: fs.readFileSync('/home/marco/myTempCerts/my.crt')
        }
      })

But I get this error:

[Vue warn]: Error in created hook: "TypeError:   
fs__WEBPACK_IMPORTED_MODULE_5___default.a.readFileSync is not a function"

image

@Florrr
Copy link

Florrr commented May 26, 2020

Sorry for confusing you..
I'll try to clarify:
If you are using "localhost" as the host (which seems to work), no ssl certificate is needed and the secure property must be false. Thus no TLS is used (Which is fine when the host server is localhost)
If you want to use an external server (with its url as the host-parameter), you need ssl certificates. SSL certificates are not included in the new Peer() constructor - since this is the client-sided library.
The snipped

ssl: {
          key: fs.readFileSync('/home/marco/myTempCerts/my.key'),
          cert: fs.readFileSync('/home/marco/myTempCerts/my.crt')
        }

is for the server sided peers-server code. e.g:

const fs = require('fs');
const { PeerServer } = require('peer');

const peerServer = PeerServer({
  port: 9000,
  ssl: {
    key: fs.readFileSync('/path/to/your/ssl/key/here.key'),
    cert: fs.readFileSync('/path/to/your/ssl/certificate/here.crt')
  }
});

Since you are using localhost, try to debug without ssl-certificates

Could you provide your full javascript-code? Otherwise it's really hard to see whats wrong

@marcoippolito
Copy link
Author

marcoippolito commented May 27, 2020

@Florrr This is the entire code related to the messages exchange between the two peer objects:

<template>
  <div>
    <template v-if=!isMobileOrTablet()>
      <h3>Desktop</h3>
      <template v-if=this.myPeer.id>
        <qriously v-bind:value="this.myPeer.id" :size="200"></qriously>
      </template>
    </template>
    <template v-else>
      <template v-if=!remotePeerId>
        <h3>MobileOrTablet</h3>
        <p class="qrError">{{ qrError }}</p>
        <p >Last result: <b>{{ remotePeerId }}</b></p>
        <qrcode-stream @decode="onDecode" @init="onQrInit" />
      </template>
    </template>
    <hr>

    <p>Message to send
      <input v-model="message">
      <button @click="sendMessage()">Send</button>
    <hr>

    <div class="col-xs-12 col-sm-6">
      <h3>Messages Flow:</h3>
      <ul class="list-group">
        <li class="list-group-item" v-for="(message, index) in messages" 
v-bind:key="index">Message: {{ message }} ({{index}})</li>
      </ul>
    </div>

  </div>
</template>

<script>
    import device from 'current-device';
    import Peer from 'peerjs';

    export default {
      props: {
        value: {
          type: [String, null],
          require: true
        }
      },
      data: () => ({
        connection: null,
        message: '',
        messages: [],
        myPeer: null,
        remotePeerId: '',
        mobilePeer: null,
    decodedContent: null,
    qrError: '',
    remotePeerId: '',
  }), 

  created() {
    //this.myPeer = new Peer()

    this.myPeer = new Peer({
      host: 'localhost',
      port: 9000,
      path: '/',
      secure: false
    })

    this.myPeer.on('open', () => {
      console.log('this.myPeer.id: ' + this.myPeer.id + ' this.myPeer.key: ' + this.myPeer.key);
    })

    // Receive messages
    this.myPeer.on('connection', con => {
      this.connection = con
      con.on('open', () => {
        con.on('data', newMessage => this.messages.push(newMessage))
      })
    })
  }, 

  methods: {
    isMobileOrTablet() {
      return (device.mobile() || device.tablet());
    },
    // vue-qrcode-reader: https://jsfiddle.net/75pcxqzu/
    onDecode (result) {
      this.remotePeerId = result;
      this.connect();
      this.qrTurnCameraOff();
    },
    async onQrInit (promise) {
      try {
        await promise
      } catch (error) {
        if (error.name === 'NotAllowedError') {
          this.error = "ERROR: you need to grant camera access permisson"
        } else if (error.name === 'NotFoundError') {
          this.error = "ERROR: no camera on this device"
        } else if (error.name === 'NotSupportedError') {
          this.error = "ERROR: secure context required (HTTPS, localhost)"
        } else if (error.name === 'NotReadableError') {
          this.error = "ERROR: is the camera already in use?"
        } else if (error.name === 'OverconstrainedError') {
          this.error = "ERROR: installed cameras are not suitable"
        } else if (error.name === 'StreamApiNotSupportedError') {
          this.error = "ERROR: Stream API is not supported in this browser"
        }
      }
    },
    qrTurnCameraOff() {
      this.camera = 'off';
    },
    connect() {
      //this.connection = this.myPeer.connect(this.remotePeerId)

      this.mobilePeer = new Peer({
        host: 'localhost',
        port: 9000,
        path: '/',
        secure: false
      })

      this.connection = this.mobilePeer.connect(this.remotePeerId);

      console.log('Now connected:', this.connection);
      // Receive messages:
      this.connection.on('open', () => {
        this.connection.on('data', newMessage => this.messages.push(newMessage))
      });
    },
    sendMessage() {
      const newMessage = {
        id: this.myPeerId,
        message: this.message
      }
      if (this.connection) {
        this.connection.send(newMessage)
      }
      this.messages.push(newMessage)
      this.message = ''
    },
    errorMsg(msg, error) {
      const errorElement = document.querySelector('#errorMsg');
      errorElement.innerHTLM += '<p>${msg}</p>';
      if (typeof error !== 'undefined') {
        console.error(error);
      }
    },
  },// end of methods object
}
</script>

.decode-result {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  max-width: 100%;

  color: white;
  font-weight: bold;
  padding: 10px;
  background-color: rgba(0,0,0,.5);
}

.qrError {
  color: red;
  font-weight: bold;
}

Both running the peerjs-server as:

npx peerjs --port 9000
Started PeerServer on ::, port: 9000, path: / (v. 0.5.3)

or as:

peerjs --port 9000 --sslkey /home/marco/myTempCerts/my.key --sslcert /home/marco
/myTempCerts/my.crt
Started PeerServer on ::, port: 9000, path: / (v. 0.5.3)

when accessing the page from another pc or laptop I get this kind of error:

GET http://localhost:9000/peerjs/id?ts=15905756285960.6529121162
peerjs.min.js?a0bc:64808378 net::ERR_CONNECTION_REFUSED

@Florrr
Copy link

Florrr commented Jun 1, 2020

Your connect() method seems to try to connect before the mobilePeer is created. Maybe try again using:

connect() {
      //this.connection = this.myPeer.connect(this.remotePeerId)

      this.mobilePeer = new Peer({
        host: 'localhost',
        port: 9000,
        path: '/',
        secure: false
      })


      console.log('Now connected:', this.connection);
      // Receive messages:
      this.connection.on('open', () => {
      this.connection = this.mobilePeer.connect(this.remotePeerId);
        this.connection.on('data', newMessage => this.messages.push(newMessage))
      });
    }

Also: I'm pretty sure such errors should be logged in the console. Consider debugging using the remote tools provided in #193 (comment)

@marcoippolito
Copy link
Author

marcoippolito commented Jun 2, 2020

Hi @Florrr

with the following vue file :

<template>
  <div>
    <template v-if=!isMobileOrTablet()>
      <h3>Desktop</h3>
      <template v-if=this.myPeer.id>
        <qriously v-bind:value="this.myPeer.id" :size="200"></qriously>
      </template>
    </template>
    <template v-else>
      <template v-if=!remotePeerId>
        <h3>MobileOrTablet</h3>
        <p class="qrError">{{ qrError }}</p>
        <p >Last result: <b>{{ remotePeerId }}</b></p>
        <qrcode-stream @decode="onDecode" @init="onQrInit" />
      </template>
    </template>
    <hr>

    <p>Message to send
      <input v-model="message">
      <button @click="sendMessage()">Send</button>
    <hr>

    <div class="col-xs-12 col-sm-6">
      <h3>Messages Flow:</h3>
      <ul class="list-group">
        <li class="list-group-item" v-for="(message, index) in messages"
          v-bind:key="index">Message: {{ message }} ({{index}})</li>
      </ul>
    </div>

  </div>
</template>

<script>
    import device from 'current-device';
    import Peer from 'peerjs';

    export default {
      props: {
        value: {
          type: [String, null],
          require: true
        }
      },
      data: () => ({
        connection: null,
        message: '',
        messages: [],
        myPeer: null,
        remotePeerId: '',
        mobilePeer: null,
        decodedContent: null,
        qrError: ''
      }),

      created() {
        //this.myPeer = new Peer()

        this.myPeer = new Peer({
          host: 'localhost',
          port: 9000,
          path: '/',
          secure: false
        })

        this.myPeer.on('open', () => {
          console.log('this.myPeer.id: ' + this.myPeer.id + ' this.myPeer.key: ' + this.myPeer.key);
        })

        // Receive messages
        this.myPeer.on('connection', con => {
          this.connection = con
          con.on('open', () => {
            con.on('data', newMessage => this.messages.push(newMessage))
          })
        })
      },

      methods: {
        isMobileOrTablet() {
          return (device.mobile() || device.tablet());
        },
        // vue-qrcode-reader: https://jsfiddle.net/75pcxqzu/
        onDecode (result) {
          this.remotePeerId = result;
          this.connect();
          this.qrTurnCameraOff();
        },
        async onQrInit (promise) {
          try {
            await promise
          } catch (error) {
            if (error.name === 'NotAllowedError') {
              this.error = "ERROR: you need to grant camera access permisson"
            } else if (error.name === 'NotFoundError') {
              this.error = "ERROR: no camera on this device"
            } else if (error.name === 'NotSupportedError') {
              this.error = "ERROR: secure context required (HTTPS, localhost)"
            } else if (error.name === 'NotReadableError') {
              this.error = "ERROR: is the camera already in use?"
            } else if (error.name === 'OverconstrainedError') {
              this.error = "ERROR: installed cameras are not suitable"
            } else if (error.name === 'StreamApiNotSupportedError') {
              this.error = "ERROR: Stream API is not supported in this browser"
            }
          }
        },
        qrTurnCameraOff() {
          this.camera = 'off';
        },
        connect() {
          this.mobilePeer = new Peer({
            host: 'localhost',
            port: 9000,
            path: '/',
            secure: false
          })

          //this.connection = this.mobilePeer.connect(this.remotePeerId);
      
          // Receive messages:
          this.connection.on('open', () => {
            this.connection = this.mobilePeer.connect(this.remotePeerId);
            console.log('Now connected:', this.connection);
            this.connection.on('data', newMessage => this.messages.push(newMessage))
          });
        },
        sendMessage() {
          const newMessage = {
            id: this.myPeerId,
            message: this.message
          }
          if (this.connection) {
            this.connection.send(newMessage)
          }
          this.messages.push(newMessage)
          this.message = ''
        },
        errorMsg(msg, error) {
          const errorElement = document.querySelector('#errorMsg');
          errorElement.innerHTLM += '<p>${msg}</p>';
          if (typeof error !== 'undefined') {
            console.error(error);
          }
        },
      },// end of methods object
    }

the connection between the peer objects doesn't happen.
And thanks to the remote tool you suggested me to use, it seems that the problem is that the Peer Object of the mobile part doesn't connect to the Peerjs-Server:

Peerjs-ErrConnectionRefused-02

Peerjs-ErrConnectionRefused-03

Peerjs-ErrConnectionRefused-04

But if I click the address of the peer-server which the peer mobile object doesn't seem to connect to, I get this:

Peerjs-ErrConnectionRefused-05

So my question is:
how to connect the second peer object, the one related to the mobile part, to the peer-server which runs after executing, on the desktop side, npx peerjs --port 9000 ?

@marcoippolito
Copy link
Author

marcoippolito commented Jun 8, 2020

With this vue file:

<template>
  <div>
    <template v-if=!isMobileOrTablet()>
      <h3>Desktop</h3>
      <template v-if=this.myPeer.id>
        <qriously v-bind:value="this.myPeer.id" :size="200"></qriously>
      </template>
    </template>
    <template v-else>
      <template v-if=!remotePeerId>
        <h3>MobileOrTablet</h3>
        <p class="qrError">{{ qrError }}</p>
        <p >Last result: <b>{{ remotePeerId }}</b></p>
        <qrcode-stream @decode="onDecode" @init="onQrInit" />
      </template>
    </template>
    <hr>

    <p>Message to send
      <input v-model="message">
      <button @click="sendMessage()">Send</button>
    <hr>

    <div class="col-xs-12 col-sm-6">
      <h3>Messages Flow:</h3>
      <ul class="list-group">
        <li class="list-group-item" v-for="(message, index) in messages"
          v-bind:key="index">Message: {{ message }} ({{index}})</li>
      </ul>
    </div>

  </div>
</template>

<script>
    import device from 'current-device';
    import Peer from 'peerjs';
    import fs from 'fs';

    export default {
      props: {
        value: {
          type: [String, null],
          require: true
        }
      },
      data: () => ({
        connection: null,
        message: '',
        messages: [],
        myPeer: null,
        remotePeerId: '',
        mobilePeer: null,
        decodedContent: null,
        qrError: ''
      }),
      created() {
        //this.myPeer = new Peer()

        this.myPeer = new Peer({
          host: 'localhost',
          port: 9000,
          path: '/',
          secure: false
        })

        this.myPeer.on('open', () => {
          console.log('this.myPeer.id: ' + this.myPeer.id + ' this.myPeer.key: ' + this.myPeer.key);
        })

        // Receive messages
        this.myPeer.on('connection', con => {
          this.connection = con
          con.on('open', () => {
            con.on('data', newMessage => this.messages.push(newMessage))
          })
        })
      },

      methods: {
        isMobileOrTablet() {
          return (device.mobile() || device.tablet());
        },
        onDecode (result) {
          this.remotePeerId = result;
          this.connect();
          this.qrTurnCameraOff();
        },
        async onQrInit (promise) {
          try {
            await promise
          } catch (error) {
            if (error.name === 'NotAllowedError') {
              this.error = "ERROR: you need to grant camera access permisson"
            } else if (error.name === 'NotFoundError') {
              this.error = "ERROR: no camera on this device"
            } else if (error.name === 'NotSupportedError') {
              this.error = "ERROR: secure context required (HTTPS, localhost)"
            } else if (error.name === 'NotReadableError') {
              this.error = "ERROR: is the camera already in use?"
            } else if (error.name === 'OverconstrainedError') {
              this.error = "ERROR: installed cameras are not suitable"
            } else if (error.name === 'StreamApiNotSupportedError') {
              this.error = "ERROR: Stream API is not supported in this browser"
            }
          }
        },
        qrTurnCameraOff() {
          this.camera = 'off';
        },
        connect() {
          this.mobilePeer = new Peer({
            host: 'https://ggc.world',
            port: 9000,
            //path: '/',
            ssl: {
              key: fs.readFileSync('/path/to/your/ssl/key/here.key'),
              cert: fs.readFileSync('/path/to/your/ssl/certificate/here.crt')
            }
          })
          // Receive messages:
          this.connection.on('open', () => {
            this.connection = this.mobilePeer.connect(this.remotePeerId);
            console.log('Now connected:', this.connection);
            this.connection.on('data', newMessage => this.messages.push(newMessage))
          });
        },
        sendMessage() {
          const newMessage = {
            id: this.myPeerId,
            message: this.message
          }
          if (this.connection) {
            this.connection.send(newMessage)
          }
          this.messages.push(newMessage)
          this.message = ''
        },
        errorMsg(msg, error) {
          const errorElement = document.querySelector('#errorMsg');
          errorElement.innerHTLM += '<p>${msg}</p>';
          if (typeof error !== 'undefined') {
            console.error(error);
          }
        },
      },// end of methods object
    </script>

I still on the mobile part: http://localhost:9000/peerjs/id?ts=15916344913130.5114210203945029 net::ERR_CONNECTION_REFUSED

Should I setup my own signaling server? Is this guide a good starting point? https://meetrix.io/blog/webrtc/how-to-setup-a-signaling-server.html

@alicera
Copy link

alicera commented Aug 13, 2020

hi ,all
does it have the protocol like ws://localhost:8000

@ZamanMehdi
Copy link

I have found a solution for a similar kind of problem. Actually, the peer server runs on HTTP protocol, and for making it run on HTTPS protocol, we need to generate an SSL key and certificate. Even after generating these things, it will only run on the localhost server and the systems connected to that network.

There is a peer server hosted on a Heroku, so it is running on HTTPS, rather than using your own peer server, we can use the path of the Heroku peer server and then host the app on some hosting website, The app will run properly. Below is my new client-side code. I also review your last attempt, I'm also quoting that attempt.

peer = new Peer({host:'peerjs-server.herokuapp.com', secure:true, port:443})

With this vue file:

<template>
  <div>
    <template v-if=!isMobileOrTablet()>
      <h3>Desktop</h3>
      <template v-if=this.myPeer.id>
        <qriously v-bind:value="this.myPeer.id" :size="200"></qriously>
      </template>
    </template>
    <template v-else>
      <template v-if=!remotePeerId>
        <h3>MobileOrTablet</h3>
        <p class="qrError">{{ qrError }}</p>
        <p >Last result: <b>{{ remotePeerId }}</b></p>
        <qrcode-stream @decode="onDecode" @init="onQrInit" />
      </template>
    </template>
    <hr>

    <p>Message to send
      <input v-model="message">
      <button @click="sendMessage()">Send</button>
    <hr>

    <div class="col-xs-12 col-sm-6">
      <h3>Messages Flow:</h3>
      <ul class="list-group">
        <li class="list-group-item" v-for="(message, index) in messages"
          v-bind:key="index">Message: {{ message }} ({{index}})</li>
      </ul>
    </div>

  </div>
</template>

<script>
    import device from 'current-device';
    import Peer from 'peerjs';
    import fs from 'fs';

    export default {
      props: {
        value: {
          type: [String, null],
          require: true
        }
      },
      data: () => ({
        connection: null,
        message: '',
        messages: [],
        myPeer: null,
        remotePeerId: '',
        mobilePeer: null,
        decodedContent: null,
        qrError: ''
      }),
      created() {
        //this.myPeer = new Peer()

        this.myPeer = new Peer({
          host: 'localhost',
          port: 9000,
          path: '/',
          secure: false
        })

        this.myPeer.on('open', () => {
          console.log('this.myPeer.id: ' + this.myPeer.id + ' this.myPeer.key: ' + this.myPeer.key);
        })

        // Receive messages
        this.myPeer.on('connection', con => {
          this.connection = con
          con.on('open', () => {
            con.on('data', newMessage => this.messages.push(newMessage))
          })
        })
      },

      methods: {
        isMobileOrTablet() {
          return (device.mobile() || device.tablet());
        },
        onDecode (result) {
          this.remotePeerId = result;
          this.connect();
          this.qrTurnCameraOff();
        },
        async onQrInit (promise) {
          try {
            await promise
          } catch (error) {
            if (error.name === 'NotAllowedError') {
              this.error = "ERROR: you need to grant camera access permisson"
            } else if (error.name === 'NotFoundError') {
              this.error = "ERROR: no camera on this device"
            } else if (error.name === 'NotSupportedError') {
              this.error = "ERROR: secure context required (HTTPS, localhost)"
            } else if (error.name === 'NotReadableError') {
              this.error = "ERROR: is the camera already in use?"
            } else if (error.name === 'OverconstrainedError') {
              this.error = "ERROR: installed cameras are not suitable"
            } else if (error.name === 'StreamApiNotSupportedError') {
              this.error = "ERROR: Stream API is not supported in this browser"
            }
          }
        },
        qrTurnCameraOff() {
          this.camera = 'off';
        },
        connect() {
          this.mobilePeer = new Peer({
            host: 'https://ggc.world',
            port: 9000,
            //path: '/',
            ssl: {
              key: fs.readFileSync('/path/to/your/ssl/key/here.key'),
              cert: fs.readFileSync('/path/to/your/ssl/certificate/here.crt')
            }
          })
          // Receive messages:
          this.connection.on('open', () => {
            this.connection = this.mobilePeer.connect(this.remotePeerId);
            console.log('Now connected:', this.connection);
            this.connection.on('data', newMessage => this.messages.push(newMessage))
          });
        },
        sendMessage() {
          const newMessage = {
            id: this.myPeerId,
            message: this.message
          }
          if (this.connection) {
            this.connection.send(newMessage)
          }
          this.messages.push(newMessage)
          this.message = ''
        },
        errorMsg(msg, error) {
          const errorElement = document.querySelector('#errorMsg');
          errorElement.innerHTLM += '<p>${msg}</p>';
          if (typeof error !== 'undefined') {
            console.error(error);
          }
        },
      },// end of methods object
    </script>

I still on the mobile part: http://localhost:9000/peerjs/id?ts=15916344913130.5114210203945029 net::ERR_CONNECTION_REFUSED

Should I setup my own signaling server? Is this guide a good starting point? https://meetrix.io/blog/webrtc/how-to-setup-a-signaling-server.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

6 participants