Search code examples
javaserverlocalhosttelnet

Telnet won't connect to localhost after I create a simple server in Java


Right now, I made a simple server in java as so:

import Java.net.*;
import Java.io.*;
import Java.util.*;

class Server{
public static void main(String[] args){
         int PORT = 13;
             try(ServerSocket server = new ServerSocket(PORT)){
                while(true){
                    try(Socket connection = server.accept()){
                         Writer out = new OutputStreamWriter(connection.getOutputStream());
                         Date now = new Date();
                         out.write(now.toString());
                         out.flush();
                         connection.close();
                     } catch(IOException ex){}
                 }
             }
             catch(IOException ex){
                System.err.println(ex);
             }
         }
    }

I compile and run this from the command line. Being on Port 13, I try to run this on telnet as so: telnet localhost 13 but all it gives me is "Connection to host lost". Mind you, I did this after enabling telnet on Windows 10 and installing it. Is there a simple step I'm missing?


Solution

  • Telnet won't connect to localhost ...

    Yes it did. That's why it said 'connection to host lost' instead of 'connection refused'.

    And here's what happened. You coded:

    connection.close();
    

    You got:

    connection to host lost

    You closed the connection; Telnet told you so.

    That's what's supposed to happen.

    There is no problem here to solve.

    Or else you got an I/O exception in the server accept loop.

    But as you are ignoring them it is impossible to say which.