我是graphql的新手...这是我的服务器文件...我无法建立套接字io连接...
当我在套接字内部进行控制时,它不会进入函数内...我认为我在这里做错了const io = require('socket.io')(server)
...
var express = require('express');
var graphqlHTTP = require('express-graphql');
var {schema} = require('../graphql/schema');
var {root} = require('../graphql/resolver');
const EventEmitter = require('events');
var app = express();
var server = require('http').Server(app);
const event = new EventEmitter()
const io = require('socket.io')(server)
event.on('event', function(action) {
console.log(action)
io.on('connection', function (socket) {
console.log('socket')
socket.emit('action', action)
})
})
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
formatError(err) {
return {
message: err.message
};
}
}));
app.use('/voyager', middleware({ endpointUrl: '/graphql' }));
app.listen(3019);
答案 0 :(得分:2)
apollo server-“ ...是使用来自任何来源的数据为GraphQL客户端快速构建可用于生产的自文档化API的最佳方法。”
apollo-server-express-将apollo用作应用程序变量的“中间件”
// Node modules imports
require('dotenv').config({ path: './variables.env' })
const express = require('express')
const socketio = require('socket.io')
const { ApolloServer, gql } = require('apollo-server-express')
// Initalizes the app server
const app = express()
const typeDefs = gql`
type Query {
foo: String
}
`;
const resolvers = {
Query: {
foo: () => 'Foo world!'
},
};
const server = new ApolloServer({ typeDefs, resolvers });
server.applyMiddleware({ app });
// Listen to port 5000, save on const to attach io to it
const http = app.listen(5000, () =>
console.log("? Server ready at http://localhost:5000" + server.graphqlPath)
)
// Attach socket.io to the server instance
const io = socketio(http)
io.on('connection', (socket) => {
// related io code
})
我强烈建议您阅读apollo
中的文档已更新@Coder
请记住,始终将所有io代码包装在io的连接方法中。
顺便说一句,您要创建两个服务器实例,一个Express和一个Http。
将服务器从express存储到const中,并用于socket.io。
const app = express()
const server = app.listen(3019)
const io = require('socket.io')(server)
io.on('connection', (socket) => {
console.log('connected to socket')
// do event here inside
// enter code here
socket.on('some_event',()=>{ // do something })
socket.on('some_event_2',()=>{ // do something 2 })
socket.on('some_event_3',()=>{ // do something 3 })
})
答案 1 :(得分:0)
const http = require("http");
const app = express();
const httpServer = createServer(app);
const io = require('socket.io')(httpServer);
io.on("connection", (socket) => {
console.log("Connected");
// your code
});
httpServer.listen(PORT, () =>
console.log(`Server stated on http://127.0.0.1:${PORT}/`)
);
您可以在快递部分引用此socket.io docs