'socketio'에 해당되는 글 3건

  1. 2015.01.27 [Node.js] net 모듈 + flash 소켓통신
  2. 2015.01.27 [nodeJS] Socket.IO 방만들기
  3. 2015.01.27 [nodeJS] Socket.IO 모듈

1. app.js

// --------------------------------------
// Imports
// --------------------------------------
var net = require('net');
var mySocket;
 
// --------------------------------------
// Construct The Socket
// --------------------------------------
// create the server and register event listeners
var server = net.createServer(function(socket) {
    mySocket = socket;
    mySocket.on("connect", onConnect);
    mySocket.on("data", onData);
});
 
// --------------------------------------
// Events
// --------------------------------------
/**
 * Handles the Event: "connect".
 *
*/
function onConnect()
{
    console.log("Connected to Flash");
}
 
/**
 * Handles the Event: "data".
 *
 * When flash sends us data, this method will handle it
 *
*/
function onData(d)
{
    if(d == "exit\0")
    {
        console.log("exit");
        mySocket.end();
        server.close();
    }
    else
    {
        console.log("From Flash = " + d);
        mySocket.write(d, 'utf8');
    }
}
 
// --------------------------------------
// Start the Socket
// --------------------------------------
server.listen(3000, "127.0.0.1");


2. flash (as3)

package
{
 
    // --------------------------------------
    // Imports
    // --------------------------------------
    import flash.display.Sprite;
    import flash.events.DataEvent;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.KeyboardEvent;
    import flash.events.MouseEvent;
    import flash.net.XMLSocket;
    import flash.text.TextField;
    import flash.ui.Keyboard;
 
    // --------------------------------------
    // Class
    // --------------------------------------
    /**
    * 

The NodeJSDemo class is ...

* */ public class NodeJSDemo extends Sprite { // -------------------------------------- // Properties // -------------------------------------- // PUBLIC GETTER/SETTERS /** * The core object which connects client to * server for real-time communication */ private var _xmlSocket:XMLSocket; /** * The sole UI element to show some test output */ private var _textField:TextField; // PUBLIC CONST // PRIVATE // -------------------------------------- // Constructor // -------------------------------------- /** * This is the constructor. * */ public function NodeJSDemo() { // SUPER super(); // EVENTS addEventListener(Event.ADDED_TO_STAGE, _onAddedToStage); // VARIABLES // PROPERTIES _textField = new TextField (); _textField.width = 300; _textField.height = 300; _textField.multiline = true; _textField.htmlText = ""; addChild(_textField); // METHODS } // -------------------------------------- // Methods // -------------------------------------- // PUBLIC /** * Handles the Event: Event.CHANGE. * * @param aEvent Event The incoming aEvent payload. * * @return void * */ private function _onAddedToStage(aEvent : Event):void { // CREATE THE SOCKET AND CONNECT - I'M NOT SURE WHAT PARAMETERS ARE VALID HERE // BUT IT MUST MATCH THE SETTINGS WITHIN THE 'HelloWorldNodeJS.js' FILE YOU ARE USING _xmlSocket = new XMLSocket("127.0.0.1", 3000); // EVENTS stage.removeEventListener(MouseEvent.CLICK, _onAddedToStage); // _xmlSocket.addEventListener(Event.CONNECT, _onConnected); _xmlSocket.addEventListener(IOErrorEvent.IO_ERROR, _onIOError); } // PRIVATE // -------------------------------------- // Event Handlers // -------------------------------------- /** * Handles the Event: Event.CHANGE. * * @param aEvent Event The incoming aEvent payload. * * @return void * */ private function _onConnected(aEvent : Event):void { // TRACE trace("onConnect() aEvent: " + aEvent); // EVENTS _xmlSocket.removeEventListener(Event.CONNECT, _onConnected); _xmlSocket.removeEventListener(IOErrorEvent.IO_ERROR, _onIOError); // _xmlSocket.addEventListener(DataEvent.DATA, _onDataReceived); _xmlSocket.addEventListener(Event.CLOSE, _onSocketClose); // stage.addEventListener(KeyboardEvent.KEY_UP, _onKeyUp); } /** * Handles the Event: Event.CHANGE. * * @param aEvent Event The incoming aEvent payload. * * @return void * */ private function _onSocketClose(aEvent : Event):void { // TRACE trace("_onSocketClose aEvent : " + aEvent); // EVENTS stage.removeEventListener(KeyboardEvent.KEY_UP, _onKeyUp); _xmlSocket.removeEventListener(Event.CLOSE, _onSocketClose); _xmlSocket.removeEventListener(DataEvent.DATA, _onDataReceived); } /** * Handles the Event: KeyboardEvent.KEY_UP. * * @param aEvent KeyboardEvent The incoming aEvent payload. * * @return void * */ private function _onKeyUp(evt:KeyboardEvent):void { // HANDLE KEYS if (evt.keyCode == Keyboard.ESCAPE) { //1. SEND 'KILL THE SERVER' TO THE SERVER _xmlSocket.send("exit"); } else { //2. SEND ANY NON-ESCAPE KEY'S CODE ('38' FOR EXAMPLE) TO SERVER // THIS IS A SILLY EXAMPLE OF SENDING A NUMBER TO THE SERVER // JUST SO THE SERVER CAN SEND IT BACK. SIMPLE. _xmlSocket.send(evt.keyCode); } } /** * Handles the Event: DataEvent.DATA. * * @param aEvent DataEvent The incoming aEvent payload. * * @return void * */ private function _onDataReceived(aEvent : DataEvent):void { try { // Show the server data in text _textField.htmlText += ("From Server: " + aEvent.data + "n"); //scroll down to show latest line _textField.scrollV = _textField.maxScrollV; } catch (error : Error) { // TRACE trace("_onDataReceived error: " + error); } } /** * Handles the Event: IOErrorEvent.IO_ERROR. * * @param aEvent IOErrorEvent The incoming aEvent payload. * * @return void * */ private function _onIOError(aEvent : IOErrorEvent):void { // TRACE trace("_onIOError aEvent: " + aEvent); // EVENTS _xmlSocket.removeEventListener(Event.CONNECT, _onConnected); _xmlSocket.removeEventListener(IOErrorEvent.IO_ERROR, _onIOError); stage.addEventListener(MouseEvent.CLICK, _onAddedToStage); } } }


'프로그래밍 > nodeJS' 카테고리의 다른 글

[nodeJS] Flash + Html5 + Node.js  (0) 2015.01.27
[nodeJS] Socket.IO 방만들기  (0) 2015.01.27
[nodeJS] Socket.IO 모듈  (0) 2015.01.27
[nodeJS] Express / Routes / Jade 모듈  (0) 2015.01.27
[nodeJS] connect / connect_router 모듈  (0) 2015.01.27
Posted by august5pm
,

>npm install socket.io 


1. server.js

// fs 모듈
var fs = require('fs');
 
// 서버생성
var server = require('http').createServer();
var io = require('socket.io').listen(server);
 
// 서버실행
server.listen(3000, function(){
    console.log('Server Running at http:127.0.0.1:3000');
});
 
// 웹 서버 이벤트 연결
server.on('request', function(request, response){
    //html 파일 읽기
    fs.readFile('index.html', function(error, data){
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.end(data);
    });
});
 
 
// 소켓서버 이벤트 연결
io.sockets.on('connection', function(socket){
    // join 이벤트
    socket.on('join', function(data){
        socket.join(data);
        socket.set('room', data);
    });
   
    // message 이벤트
    socket.on('message', function(data){
        socket.get('room', function(error, room){
            io.sockets.in(room).emit('message', data); 
        });
    });
});


2. index.html

<!DOCTYPE HTML>
<html>
 <head>
  <title> SOCKET.IO ROOM </title>
  <meta charset="utf8" />
  <script src="/socket.io/socket.io.js"></script>
  <script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
  <script>
    $(document).ready(function(){
        //변수선언
        var room = prompt('방 이름을 입력하세요.','');
        var socket = io.connect();
 
        //소켓 이벤트 연결
        socket.emit('join', room);
        socket.on('message', function(data){
            $('<p>'+data+'</p>').appendTo('body');
        });
 
        //버튼 이벤트
        $('#btn').click(function(){
            var msg = $('#msg').val();
            socket.emit('message', msg);
        });
    });
  </script>
 </head>
 
 <body>
  <input id="msg" type="text" style="width:100px;" />
  <input id="btn" type="button" value="send" />
 </body>
</html>  
Posted by august5pm
,

>npm install connect 

>npm install connect_router

>npm install socket.io


1. app.js

/*
    폴더구조
    1. html - html 페이지
    2. node_modules - nodejs 모듈
    3. Resource - js, css, images 등의 리소스 파일
*/
 
// http 서비스를 하기 위해
var connect = require("connect"),
    connect_router = require("connect_router"),
    fs = require("fs"),
    url = require("url");
 
//서버 객체를 얻어옵니다.
var server = connect.createServer()
.use(connect.static(__dirname + "/Resource")) // 각종 리소스 폴더
.use(connect.bodyParser()) // post 방식 전송된 데이터 읽어오기 위해
.use(connect_router(main)) // 페이지 라우팅 처리할 함수
.use(connect.errorHandler({stack:true, message:true, dump:true})) // 에러출력 및 처리
.listen(3000);
 
//페이지 라우팅을 해서 클라이언트에 서비스할 함수
function main(app){
    app.get("/", function(request, response){
        console.log("index.html 클라이언트의 요청이 왔습니다.");
        //클라이언트에 응답할 html 파일을 읽어서 응답한다.
        fs.readFile("html/index.html", function(error, data){
            response.writeHead(200, {"Content-Type":"text/html"});
            response.end(data);
        });
    });
}
 
/*
 * 클라이언트와 웹소켓 연결을 하기 위한 작업
 */
 
//필요한 모듈을 얻어온다.
var socketio = require("socket.io");
 
// 클라이언트와 소켓 통신을 하기 위한 io 객체를 얻어온다.
var io = socketio.listen(server);
 
//불필요한 로그는 제거 하기 위해
io.set("log level", 2);
 
// 클라이언트가 소켓 서버 접속을 하면 'connection' 이벤트가 발생한다.
io.sockets.on('connection', function(socket){
    /*
     * 클라이언트의 이벤트에 귀를 귀울이거나, 혹은 이벤트를 발생시키면 된다.
     *
     * 3가지 통신 방법
     * 1. public => io.sockets.emit("이벤트명", data);
     * 2. broadcast => io.broadcast.emit("이벤트명", data);
     * 3. private => io.sockets.sockets[id].emit("이벤트명", data);
     */
    console.log("connection");
   
    socket.on('name', name);
 
    //when the user disconnects.. perform this
    socket.on('disconnect', function(){
        console.log('disconect');
    });
 
    function name($data){
        socket.emit('name', $data);
    }
});


2. /html/index.html

<!DOCTYPE HTML>
<html>
 <head>
  <title> socket.io </title>
  <script src="/socket.io/socket.io.js"></script>
  <script src="/js/jquery-1.8.0.min.js"></script>
  <script>
    $(document).ready(function(){
        var socket = io.connect('http://127.0.0.1:3000');
   
        // on connection to server, ask for user's name with an anonymous callback
        socket.on('connect', function(){
           
        });
       
        // addEventListener(event, callback)
        socket.on('name', name);
 
        $('#btn_send').click(function(){
            var inputValue = $('#input_text').val();
            socket.emit('name', inputValue);
        });
 
        function name($data){
            $("#result_text").html($data);
        }
    });
  </script>
 </head>
 
 <body>
    <input id="input_text" style="width:100px;" />
    <input id="btn_send" type="button" value="send" />
    <div id="result_text">result</div>
 </body>
</html>

'프로그래밍 > nodeJS' 카테고리의 다른 글

[Node.js] net 모듈 + flash 소켓통신  (0) 2015.01.27
[nodeJS] Socket.IO 방만들기  (0) 2015.01.27
[nodeJS] Express / Routes / Jade 모듈  (0) 2015.01.27
[nodeJS] connect / connect_router 모듈  (0) 2015.01.27
[nodeJS] jade 모듈  (0) 2015.01.27
Posted by august5pm
,