這裏是我在Heroku和AppFog上託管的node.js TCP服務器的代碼。我的客戶端是用C編寫的,它只是向服務器發送消息並獲得響應。當我在本地託管服務器時,它們工作正常。但是,當我嘗試連接到在線服務器時,客戶端失敗(「ERROR連接:操作超時」)。任何想法發生了什麼?Heroku/AppFog上的Node.js TCP服務器
服務器(node.js中):
var net = require('net');
var server = net.createServer(function (socket) {
socket.on("data", function(data){
socket.write(data.toString());
});
});
var port = process.env.VCAP_APP_PORT || 8081;
console.log(port);
server.listen(port);
客戶端(C,從http://www.linuxhowtos.org/C_C++/socket.htm):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
while (1){
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
}
close(sockfd);
return 0;
}
我在我的本地機器上運行你的代碼,它工作。超時表示您的服務器無法訪問。檢查您是否使用正確的地址並允許訪問。 – user568109