我的Node.js服务器连接到由C开发的unix套接字。在每个HTTP请求中,参数将发送到C程序并接收响应并发送给客户端。
但是在第一次请求之后,套接字会自动断开连接。断开连接的原因是什么,有什么方法可以阻止它吗?
domain_socket.C
include statement..
int main(){
/* delete the socket file */
unlink("/tmp/server_socket");
/* create a socket */
int server_sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un server_addr;
server_addr.sun_family = AF_UNIX;
strcpy(server_addr.sun_path, "/tmp/server_socket");
/* bind with the local file */
bind(server_sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
/* listen */
listen(server_sockfd, 5);
char data[100];
char res[100];
int client_sockfd;
struct sockaddr_un client_addr;
socklen_t len = sizeof(client_addr);
while (1) {
printf("server waiting:\n");
/* accept a connection */
client_sockfd = accept(server_sockfd, (struct sockaddr*)&client_addr, &len);
/* dummy data processing */
read(client_sockfd, data, 100);
printf("Received data: \"%s\"\n", data);
sprintf(res, "path: %s", data);
printf("send \"%s\" to client.\n", res);
write(client_sockfd, res, strlen(res));
/* close the socket */
close(client_sockfd);
}
return 0;
}
app.js
/* require statement */
var app = express();
var client = net.createConnection("/tmp/server_socket");
client.on('connect', function() {
console.log('Connected to socket');
});
client.on('end', function() {
console.log('disconnected');
client = net.createConnection("/tmp/server_socket");
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var router = express.Router();
router.get('/query', function(req, res, next) {
client.write("/home/user/queries/108100.png");
client.on('data', function(data) {
res.send(data.toString());
});
});
app.use('/', router);
module.exports = app;