2017-12-31 86 views
1

클라이언트 측과 서버 측 소켓 연결에 문제가 있습니다.클라이언트 측과 서버 측 연결이 socket.io에서 작동하지 않습니다.

var app = require('express')(); 
var http = require('http').Server(app); 
var io = require('socket.io')(http); 

io.on('connection', function(socket) { 
    console.log('a user connected'); 

    socket.on('disconnect', function(){ 
    console.log('user disconnected'); 
    }); 
}); 

http.listen(3000, function(){ 
    console.log('listening on *:3000'); 
}); 

및 클라이언트 측에이 코드 : - - :

나는 서버 측에이 코드가

<html> 
<body> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.js"></script> 
    <script> 
     var socket = io(); 
    </script> 
</body> 
</html> 

서버 측의 코드가 작동을하지만, 클라이언트 -에서 난이 오류가 있습니다 : - enter image description here

아무도 내가 문제를 해결하는 데 도움이 될 수 있습니까? 덕분에 많은 :(당신이 실제로 당신이 당신의 HTML을 제공하기위한 경로를 지정하지 않습니다. 직접 브라우저에 파일을 열 것 같은

+0

브라우저 콘솔에서 오류가 도움이 될 것입니다 희망? –

+0

아니요. 브라우저 콘솔에 오류가 없습니다 –

+0

불행히도 .. 같은 문제가 –

답변

0

그것 보인다. 그 socketio 그렇게 할 수있다 POST 및 설문 조사 데이터.

app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); });

동일한 포트에서 nodej를 통해 서비스하는 대신 브라우저에 파일을 직접 열어야하는 경우 클라이언트 측 소켓에 호스트와 포트를 지정해야합니다. io()을 사용하는 것보다는 클라이언트 측 소켓에서 호스트와 포트를 지정해야합니다. io()을 사용하면 전자이

var socket = io("http://localhost:3000");

+0

같은 문제가 발생합니다. –

+0

@ alial-shelleh 나는 당신의 코드를 시험해 보았고 나를 위해 잘 작동했다. 클라이언트 측 편집을위한 해결책을 시도하십시오. – owaishanif786

+0

죄송합니다 ..하지만 같은 오류가 있습니다 :/ –

0

그래서 여기 저

// server 

const app = require('express')(); 
const http = require('http').createServer(app); 
//       ^^^^^^^^^^^^ 
const io = require('socket.io')(http); 

// here you should serve your index.html file 
// and the socket io will know which socket to track 
app.get('/', function(req, res){ 
    res.sendFile(__dirname + '/index.html'); 
}); 

io.on('connection', function(socket){ 
    console.log('a user connected'); 
}); 

http.listen(3000, function(){ 
    console.log('listening on *:3000'); 
}); 

// client/index.html 
<!doctype html> 
<html> 
    <head> 
    <title>Socket.IO chat</title> 
    <script src="/socket.io/socket.io.js"></script> 
    <script> 
     // here it automatically track localhost:3000 
     var socket = io(); 
    </script> 

    </head> 
    <body> 
    <ul id="messages"></ul> 
    <form action=""> 
     <input id="m" autocomplete="off" /><button>Send</button> 
    </form> 
    </body> 
</html> 

위해 어떻게 작동하는지 당신에게

관련 문제