0

我正在编写一个简单的客户端-服务器程序,我的问题是服务器不等待客户端的回答,这会导致IOException. 服务器尝试执行时发生异常

line = bufferStringFromClientReader.readLine();

我究竟做错了什么?

服务器

import java.io.*;
import java.net.*;

public class Server {

    private final static String filePath = "dataFile.txt";

    public static void main(String[] arg) {
    ServerSocket serverSocket = null;
    Socket serverConnection = null;
    OutputStream outServerStream = null;
    InputStream inServerStream = null;
    PrintWriter printWriterDataSender = null;
    BufferedReader bufferDataFromFileReader = null;
    BufferedReader bufferStringFromClientReader = null;
    BufferedWriter bufferedStringToFileWriter = null;
    String line;

    try {
        serverSocket = new ServerSocket(8868);
    } catch (IOException e) {
        throw new RuntimeException("Nieobsłużony wyjątek - nie można utowrzyć gniazda serwera");
    }

    try {
        serverConnection = serverSocket.accept();
    } catch (IOException e) {
        throw new RuntimeException("Nieobsłużony wyjątek - nie można nawiązać połączenia z klientem");
    }

    try {
        inServerStream = serverConnection.getInputStream();
    } catch (IOException e) {
        throw new RuntimeException("Nieobsłużony wyjątek - nie można pobrać strumienia wejścia");
    }

    try {
        outServerStream = serverConnection.getOutputStream();
        bufferDataFromFileReader = new BufferedReader(new FileReader(filePath));
        bufferedStringToFileWriter = new BufferedWriter(new FileWriter(filePath, true));
    } catch (IOException e) {
        throw new RuntimeException("Nieobsłużony wyjątek - nie można pobrać strumienia wyjścia");
    }

    while (true) {

        try {
                printWriterDataSender = new PrintWriter(outServerStream);
                line = bufferDataFromFileReader.readLine();    
                printWriterDataSender.println(line);
                printWriterDataSender.flush();
                printWriterDataSender.close();;

                bufferStringFromClientReader = new BufferedReader(new InputStreamReader(inServerStream));

                System.out.println("get answer from client");

                line = bufferStringFromClientReader.readLine();

                bufferedStringToFileWriter.write(line);
                bufferedStringToFileWriter.close();

        } catch (Exception e) {

            System.out.println("utracono polaczenie");
            try {
                serverConnection = serverSocket.accept();
            } catch (IOException e1) {
                throw new RuntimeException("Nieobsłużony wyjątek - nie można nawiązać połączenia z klientem");
            }

            try {
                inServerStream = serverConnection.getInputStream();
            } catch (IOException e2) {
                throw new RuntimeException("Nieobsłużony wyjątek - nie można pobrać strumienia wejścia");
            }

            try {
                outServerStream = serverConnection.getOutputStream();
            } catch (IOException e3) {
                throw new RuntimeException("Nieobsłużony wyjątek - nie można pobrać strumienia wyjścia");
            }
        } 
    }
}}

客户

import java.awt.EventQueue;
import java.io.*;
import java.util.*;
import java.net.*;
import javax.swing.*;


public class Client {

public static void main(String[] args) 
{

     Socket clientSocket = null;
     InputStream clientInputStream = null;
     OutputStream clientOutputStream = null;
     BufferedReader clientBufferReader = null; 

    try
    {
        clientSocket = new Socket("localhost", 8868);
    }
    catch(UnknownHostException e)
    {
        throw new RuntimeException("Nieobsłużony wyjątek - nieznana nazwa hosta");
    }
    catch(IOException e)
    {
        throw new RuntimeException("Nieobsłużony wyjątek - nie można utowrzyć gniazda klienta");
    }

    try
    {
        clientInputStream = clientSocket.getInputStream();
    }
    catch(IOException e)
    {
        throw new RuntimeException("Nieobsłużony wyjątek - nie można pobrać strumienia wejścia");
    }

    try
    {
        clientOutputStream = clientSocket.getOutputStream();
    }
    catch(IOException e)
    {
        throw new RuntimeException("Nieobsłużony wyjątek - nie można pobrać strumienia wyjścia");
    }

    try
    { 
        clientBufferReader = new BufferedReader(new InputStreamReader(clientInputStream)); 
    }
    catch(Exception e)
    {
        throw new RuntimeException("Nieobsłużony wyjątek - nie można utworzyć bufora odczytu danych od serwera");             
    }

    try
    { 
        String tmpString = clientBufferReader.readLine();
        System.out.println(tmpString);



        PrintWriter answer = new PrintWriter(clientOutputStream);

        answer.println("ans \n");
        answer.close();


    }
    catch(Exception e)
    {
        throw new RuntimeException("Nieobsłużony wyjątek - odpowiedz");             
    }  
}
4

2 回答 2

1

问题是您PrintWriter过早地关闭了服务器。这样做会阻止从 Socket 读取任何数据InputStream

printWriterDataSender.close();

所有操作完成后将其移至finally块将解决问题。确保在此之后发生:Socket IOsocket.close

printWriterDataSender.close();
bufferStringFromClientReader.close();
serverConnection.close(); // last call

此外,完成此操作后,您可能需要进行一次读取。目前您正在while循环读取和写入,但客户端只写入一次。这将导致Socket读取异常。

另请参阅:读取和写入套接字

于 2013-04-13T16:45:04.563 回答
0

在您的客户端PrintWriter answer = new PrintWriter(clientOutputStream, true );中启用自动刷新行为。客户端和服务器都可以使用此功能;刷新是在您的代码服务器端由pw.flush().

为了在 SO 中更清晰易读,您可以按如下方式编写代码,这是您的客户端和服务器重写,并且可以正常工作!

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Client {

   static final CountDownLatch cdl = new CountDownLatch( 1 );

   static class Server extends Thread {

      @Override
      public void run() {
         try( ServerSocket serverSocket = new ServerSocket( 8868 )) {
            cdl.countDown();
            Socket         serverConnection = serverSocket.accept();
            OutputStream   outServerStream  = serverConnection.getOutputStream();
            InputStream    inServerStream   = serverConnection.getInputStream();
            PrintWriter    dataSender       = new PrintWriter( outServerStream, true );
            BufferedReader clientReader     = new BufferedReader( new InputStreamReader( inServerStream ));
            dataSender.println( "Hello, " );
            System.out.println( "SERVER: " + clientReader.readLine());
            serverConnection.close();
         }
         catch( IOException x ) {
            x.printStackTrace();
         }
      }
   }

   public static void main( String[] args ) throws Exception {
      new Server().start();
      cdl.await( 1, TimeUnit.DAYS );

      Socket         clientSocket       = new Socket( "localhost", 8868 );
      InputStream    clientInputStream  = clientSocket.getInputStream();
      OutputStream   clientOutputStream = clientSocket.getOutputStream();
      PrintWriter    answer             = new PrintWriter( clientOutputStream, true );
      BufferedReader clientBufferReader = new BufferedReader( new InputStreamReader( clientInputStream ));
      System.out.println( "CLIENT: " + clientBufferReader.readLine());
      answer.println( "world!" );
      clientSocket.close();
   }
}

输出:

CLIENT: Hello, 
SERVER: world!
于 2013-04-13T16:28:41.153 回答