如何在netbeans telnet上运行客户端和服务器代码

时间:2014-03-02 14:48:01

标签: java port telnet

以下是 link ,我正在编写一个使用telnet的Java / Netbeans中的简单程序,但我一直遇到同样的错误。我在这里做错了什么? 我刚刚为每个人制作了2个.java文件,并且我试图在net beans中运行它来按下run 1

  • 线程“main”中的异常java.net.ConnectException:Connection 拒绝:连接

    Telnet客户端 Telnet客户端 //此代码连接到telnet服务器并在输入命令“1”时接收数据

    import java.net.*;
    import java.io.*;
    
    class TelnetClient
    {
        public static void main(String args[]) throws Exception
        {
            //Create object of Socket
            Socket soc=new Socket("localhost",8088);
            String Command;
            //Create object of Input Stream to read from socket
            DataInputStream din=new DataInputStream(soc.getInputStream());   
            //Create object of Output Stream  to write on socket
            DataOutputStream dout=new DataOutputStream(soc.getOutputStream());
            // Object of Buffered Reader to read command from terminal
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Welcome to Telnet Client");
            System.out.println("< Telnet Prompt >");
            Command=br.readLine();//reads the command
            dout.writeUTF(Command);//sends command to server
            System.out.println(din.readLine()); //gets the response of server       
            soc.close();  //close port 
            din.close();  //close input stream      
            dout.close(); //close output stream     
            br.close();  //close buffered Reader   
        }
    }
    

    Telnet服务器 //每当客户端连接它时,此代码都会向客户端发送一个字符串 //当收到命令“1”时,将响应发送给客户端

    import java.lang.*;
    import java.io.*;
    import java.net.*;
    
    class TelnetServer {
       public static void main(String args[]) {
       String data = "Hello Client!! ";
       try {
          // Create object of Server Socket
         ServerSocket srvr = new ServerSocket(8088);
          // Socket object that listens the port (8088) and accepts the incoming connection
          //requests
         Socket skt = srvr.accept();
         System.out.println("Client Connected!");
         // gets output stream object 
         PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
         //gets input stream object   
         DataInputStream din=new DataInputStream(skt.getInputStream());       
         if(din.readUTF().equals("1")){ 
         // sends response to incoming request if command is '1'   
    
         System.out.println("String: '" + data);
         out.print(data);
         }
         out.close();// clos out
         skt.close();// close skt
         srvr.close();// close srvr
         din.close(); // close din
      }
      catch(Exception e) {
         System.out.print(e);
      }
    

    } }

0 个答案:

没有答案