Napisałem taki serwer echa w C++ działającym pod Linuksem:
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> // struct sockaddr_in
#include <unistd.h>
using namespace std;
/*
* Simple echo server: toupper.
*/
#define PORT 1000
int main()
{
int sockfd, newsockfd;
sockaddr_in server = {AF_INET, PORT, INADDR_ANY};
pid_t pid;
if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ) {
cerr << "Socket call failed" << endl;
exit(1);
}
// bind socket with server address
if( bind(sockfd, (sockaddr*) &server, sizeof(sockaddr_in)) == -1 ) {
cerr << "bind call failed" << endl;
exit(1);
}
// start listen
if( listen(sockfd, 5) == -1 ) {
cerr << "listen call failed" << endl;
exit(1);
}
// start accept loop
char c;
for(; ;) {
if( (newsockfd = accept(sockfd, NULL, NULL)) == -1) {
cerr << "accept call failed" << endl;
continue;
}
// create child for new connection
switch(pid = fork()) {
case 0:
// child code: recieve data and send them back
while( recv(newsockfd, &c, 1, 0) > 0 ) {
cout << c;
c = toupper(c);
// send it back!
send(newsockfd, &c, 1, 0);
}
break;
default:
// parent code
break;
}
}
return 0;
}
Kod kompiluje się, ale raczej nie działa albo źle obsługuję telnet. Chcąc podłączyć się wykonuje następujące polecenie:
$ telnet 127.0.0.1 1000
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
Gdy wykonam analogiczne połączenie na serwer SMTP to odzywa się sendmail (tyle, że podaje port 25).
Usługa cały czas działa tzn. w oknie obok proces serwera jest aktywny.
Co to może być?
Pozdrawiam,