2016-12-16 1 views
0

그래서 socket.io를 사용하여 node.js 서버를 만들고 싶습니다.하지만 초보자에 가깝고 구문 적으로 혼동 스럽지만 특급 패키지를 찾으십시오. 나는 익스프레스와 app.js를 사용하는 법을 배워야하지만, http, js, socket.io 패키지에만있는 node.js의 기능에 도달 한 후에 그렇게 할 계획이다. 거의 한 시간 동안 온라인에서 봤는데 내 문제를 해결하는 데 도움이되지 않았습니다. socket.io에서 가지고있는 주된 문제점은 클라이언트 측에서 함수 io(); 작동 안됨. body 태그 위의 스크립트 링크 경로를 내 서버 프로젝트의 디렉토리에있는 파일로 리디렉션하려고 시도했지만 require() 오류가 반환되었습니다. 함수가 아닙니다. 나는이 텍스트 틀 아래에서 내가 사용하고있는 파일들 (모두는 아님)을 포함시켰다. 이 형식이 잘못되었거나 틀린 경우 용서해주십시오. 스택 교환을 사용하여 질문하는 것이 처음이기 때문에 용서해주십시오. 이런 이유로, 여기에 따르는 형식에 더 적합하게 편집하려면 충분한 평판이 있다면 그렇게하십시오.Socket.io는 표현식이없는 node.js를 사용하고 있습니까?

첫째, 내 서버에 파일 :

const http = require('http'); 
const fs = require('fs'); 
const io = require('socket.io')(http); 

function socketReq(soc){ 
    soc.emit("test", {"user":"test", "text":"testing da socket"}); 
} 

io.on("connection", socketReq); 

function server(req,res){ 
    console.log('A user tried to connect to mazeserver.localtunnel.me'+req.url) 
    if(req.url == '/'){ 
     console.log('Sending html...'); 
     res.writeHead(200, {"Context-Type":"text/html"}); 
     fs.createReadStream('./index.html').pipe(res); 
    }else if(req.url == '/pong.js'){ 
     console.log('Sending JS...'); 
     res.writeHead(200, {"Context-Type":"text/JavaScript"}); 
     fs.createReadStream('./pong.js').pipe(res); 
    }else { 
     console.log('Error 404: file .'+req.url+' not found'); 
     res.writeHead(404, {"Context-Type":"text/html"}); 
     fs.createReadStream('./404.html').pipe(res); 
    } 
} 

http.createServer(server).listen(1337); 
console.log('Server created'); 

그리고 지금, 내 주요 html 파일 :

<html id='html'> 
    <head> 
     <title>Maze server</title> 
     <center> 
     <hr><br> 
     <h1>Welcome to my test server!</h1> 
     <br><hr> 
     <p>This is some text to test</p> 
     </center> 
     <script type='text/JavaScript'> 
      document.getElementById('html').style.hide = "true"; 
      document.onload = function(){ 
       document.getElementById('html').style.hide = "false"; 
      } 
      var clicks = 0; 
      function clickButton(){ 
       clicks++; 
       document.getElementById('clicks').innerHTML = clicks; 
      } 
     </script> 
    </head> 
    <script src="/socket.io/socket.io.js"></script> 
    <script> 
     var socket = io(); 
    </script> 
    <body> 
     <center> 
     <button onClick='clickButton();'>Im a button</button> 
     <p>You've clicked me <span id='clicks'>0</span> times. Ouch!</p> 
     <br><hr> 
     <p>Test canvas:</p> 
     <canvas id='canvas' width='400' height='200'></canvas> 
     <script src='pong.js' type='text/JavaScript'></script> 
     <br> 
     <br> 
     <button onClick='bounce();'>Bounce!</button> 
     <br> 
     <button onClick='speed("x");'>Speed up X</button> 
     <button onClick='speed("y");'>Speed up Y</button> 
     <br> 
     <button onClick='speed("x"); speed("y");'>Speed up both</button> 
     <br> 
     <button onClick='resetXY();'>Reset</button> 
     <br><hr> 
     </center> 
     <p>"Copyrite" <strong><blink type='EasterEgg' mazeiness='true'>MazeOfEncryption</blink></strong> 2048. Because why the heck not.</p> 
    </body> 
</html> 

파일이 추가로 필요한 경우, 나는이 포함되어야 어떤 파일 말해 줘요 I 을하지만은이 두 파일 중 하나에 문제가 있다고 가정합니다. 미리 감사드립니다,

-Maze

+0

당신은 방법을 찾아 socket.io 사양으로 볼 수있다. 왜냐하면'express '에 첨부 할 때 몇 개의 핸드 쉐이킹 POST와 GET 요청을 처리하기위한 경로가 추가되기 때문입니다. –

+0

기본적으로 표현식없이 제대로 작동하려면 몇 가지를 추가해야합니다. 당신은 더 구체적 일 수 있습니까? – Programah

+0

socket.io 문서의 오른쪽 : http://socket.io/docs/#using-with-node-http-server. Socket.io는 일반 HTTP 서버와 함께 사용되며 익스프레스가 없습니다. 또는 자신의 웹 서버를 만들지 않고도 : http://socket.io/docs/#using-it-just-as-a-cross-browser-websocket (socket.io는 자체를 만듭니다). 참고로, socket.io가 아닌 다른 URL을 처리해야하는 경우 Express는 실제로 제공되는만큼 쉽습니다. 그렇지 않다면 socket.io와 함께 일반 http 서버를 사용할 수 있습니다. – jfriend00

답변

2

당신이 npm에 의해 socket.io을 설치해야합니다뿐만 아니라 socket.io 클라이언트를 가지고있다. 확실히 당신은 CDN에 socket.io 클라이언트를 사용할 수 있습니다 :

서버 측
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script> 

, socket.io는 app 인스턴스를 부트 스트랩하지만 http한다. 는 예컨대 :

var http = require('http'); 
var socket = require('socket.io'); 
function server()... 
app = http.createServer(server); 
io = socket(app); 
app.listen(80); 

기본값은 그들이 그냥 var socket = io('http://localhost'); 같이 localhost를 지정 포트 (80) 그래서 클라이언트 측에서 사용합니다. 다른 포트를 사용하려면 io 인스턴스를 변경해야합니다. 예컨대

var socket = io('http://localhost:1337')

+0

감사! 이것은 효과가 있었다. 내가 아직도 가지고있는 유일한 문제는 포트를 80에서 1337로 변경하는 방법을 알아 내려고하는 것이지만, 나는 온라인 어딘가에서 그 포트를 찾을 수있을 것이라고 확신한다. 내가 필요한 이유는 localtunnel.me를 사용하여 다른 사람들에게 로컬 포트를 호스트 할 수 있기 때문입니다. 권한 오류로 인해 80 번으로 처리하지 못하는 것 같습니다. 아마 주위를 둘러 보면서이를 수정할 수는 있지만, 이것이 작동하는 이유와 그것을 해결하는 방법을 알면 도움이 될 것입니다. – Programah

+1

또한, io = socket(); did not는 작동하지만, 어떤 이유로 socket = io(); 않았다 : P – Programah