套接字关闭异常和EOF异常

时间:2019-01-30 17:47:11

标签: java serversocket

我一直在用Java编写基本的文本传输代码,但我无法理解代码中的错误。

服务器端程序和客户端程序具有相同的发送和接收代码。

服务器:

ServerSocket ss = new ServerSocket(44444);
System.out.println("Waiting...");
Socket s = ss.accept();
System.out.println("Connected!\n\n");

DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Thread send = new Thread(new Runnable()
{
   public void run()
   {
      try
      {
         String tx = "";
         while(!tx.equalsIgnoreCase("Over"))
         {
            tx = br.readLine();
            if(tx.equals(""))
               continue;
            dout.writeUTF(tx);
            dout.flush();
         }
      }
      catch(Exception e)
      {
         e.printStackTrace();
      }

   }
};

Thread receive = new Thread(new Runnable()
{
   public void run()
   {
      try
      {
         String rx = "";               
         while(!rx.equalsIgnoreCase("Over"))
         {
            rx = din.readUTF();
            System.out.println("Server: " + rx);
         }
      }
      catch(Exception e)
      {
         e.printStackTrace();
      }
   }
});

send.start();
receive.start();

if(!send.isAlive()||!receive.isAlive())
{
   din.close();
   dout.close();
   ss.close();
}

客户:

Socket s = new Socket("localhost",44444);
System.out.println("Connected!\n\n");

Scanner in = new Scanner(System.in);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Thread send = new Thread(new Runnable()
{
   public void run()
   {
      try
      {
         String tx = "";
         while(!tx.equalsIgnoreCase("Over"))
         {
            tx = br.readLine();
            if(tx.equals(""))
               continue;
            dout.writeUTF(tx);
            dout.flush();
         }
      }
      catch(Exception e)//Itha catch zala exception
      {
         e.printStackTrace();
      }

      System.out.println("a");

    }
});

Thread receive = new Thread(new Runnable()
{
   public void run()
   {
      try
      {
         String rx = "";               
         while(!rx.equalsIgnoreCase("Over"))
         {
            rx = din.readUTF();
            System.out.println("Server: " + rx);
         }
      }
      catch(Exception e)
      {
         e.printStackTrace();
      }
   }
});

send.start();
receive.start();     

if(!send.isAlive()||!receive.isAlive())
{
   din.close();
   dout.close();
   s.close();
}

“ din.readUTF();”上的异常 该消息应该被发送,但是只是抛出EOFexception和SocketException:套接字已关闭。

编辑:已上传完整代码

0 个答案:

没有答案