1
0

More than 5 years have passed since last update.

ubuntu+nodejs+express+socketioでサンプルページ

Last updated at Posted at 2019-02-27

備忘録

目的:herokuへのアップロードのテストをするために、通信のできるサンプルページを作る

やりかた:
virtualboxとubuntuのディスクをダウンロード
仮想マシンを作成、起動
右クリック→端末を起動
下記を順に実行していく

$sudo apt-get install nodejs npm

 //nodejsとnpmをインストールする、バージョンは知らない

$npm install -g express

 //expressをインストールする、バージョンは知らない

$express hoge[任意のフォルダ名]

 //任意のフォルダを作成する

$cd hoge

 //hoge内に移動

$ls hoge

 //hogeフォルダの内容を表示
 //app.js bin package.json public views routes となっていたらOK

$npm install --save socket.io

 //socket.ioをインストール

//いじる場所はviews/index.jadeと、bin/www

bin/wwwの末尾に以下を足す(サーバー側の処理になる)

bin/www(追記)

var io = require('socket.io').listen(server);

io.sockets.on('connection', function(socket) {

  socket.emit('greeting', function (a) {
    console.log('connection clear');
    console.log(a)
  });

  socket.on('client_to_server', function(){
    var tom ='hello';
    console.log('button pushed');
    socket.emit('server_to_client', tom);

  })
});

io.sockets.on('connection')は接続がうまく行ったときにサーバーに送られる'connection'に対して起動している
各処理はこの中に書くと動く

index.jadeを書き換える、テスト用のソースを以下に記載

views/index.jade
doctype html
html
  head
    title Socket.IO Test
    script(src='//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js')
    script(src='/socket.io/socket.io.js')
    script.
      var socket = io.connect();

      socket.on('greeting', function() {
       console.log('hello world')
      });

      function button(){
      console.log('pushed')
      var a=1
      socket.emit('client_to_server',a)
      }

      socket.on('server_to_client', function(tom){
      console.log(tom)
      })


  body
    h1 Socket.IO Test
    input(type='button', onclick='button()', value='叩いてコンソールを出力')

scriptの二行目で、socket.ioを読み込んでいる。詳しいことはわからない。

//いじる

$ npm start

 //自家サーバーを起動、

ブラウザから
http://localhost:3000
を開くと、ページが表示されている

(もし、

Error: Cannot find module 'static-favicon'

とかが出てきていたら、

$ npm install

で、必要なモジュールが全部インストールされる。)

ボタンを押すと各種コンソールが出力される

これをherokuにあげたいぞ

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0