Java Client-Server Socket只能发送1个文件

时间:2017-01-21 13:07:37

标签: java sockets server client

我正在做一个示例客户端 - 服务器套接字项目,其中服务器将文件发送到客户端,客户端将其保存在目标文件夹中。它运作良好但它仅适用于 ONCE 。我必须重新启动服务器并重新连接客户端才能发送另一个文件。

我做错了什么?

服务器

public void connect() {
        int retryCount = 0;

        while (!isConnected) {
            if (retryCount < 5) {
                try {
                    socket = new Socket(currentIPAddress, currentPort);

                    outputStream = new ObjectOutputStream(socket.getOutputStream());
                    inputStream = new ObjectInputStream(socket.getInputStream());
                    isConnected = true;

                    //connection success
                    String command = inputStream.readUTF();

                    if (command.equals("newfile")) {
                        this.clientCmdStatus.setText("Received a file from Server");
                        outputStream.writeUTF("Thanks Server! Client Received the file");
                        outputStream.flush();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                        new Thread(new DownloadingThread()).start();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                    retryCount++;
                }
            } else {
                //Timed out. Make sure Server is running & Retry
                retryCount = 0;
                break;
            }
        }
    }

我用来从服务器发送文件的方法

public void downloadFile() {
        try {
            fileEvent = (FileEvent) inputStream.readObject();
            if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
                System.out.println("Error occurred ..So exiting");
                System.exit(0);
            }

            String outputFile = destinationPath + fileEvent.getFilename();

            if (!new File(destinationPath).exists()) {
                new File(destinationPath).mkdirs();
            }

            dstFile = new File(outputFile);
            fileOutputStream = new FileOutputStream(dstFile);
            fileOutputStream.write(fileEvent.getFileData());
            fileOutputStream.flush();
            fileOutputStream.close();
            System.out.println("Output file : " + outputFile + " is successfully saved ");
            serverResponsesBox.setText("File received from server: " + fileEvent.getFilename());

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

客户端

#define PWM_QUANTA = 400 ; // 5us
static volatile uint8_t brightness = 150 ;
static Clock_Handle myClock ;


void setBrightness( uint8_t br )
{
  brightness = br ;
}

void SetUp(void)
{
  SysCtlClockSet(SYSCTL_SYSDIV_2_5|SYSCTL_USE_PLL|SYSCTL_OSC_MAIN|SYSCTL_XTAL_16MHZ);
  GPIOPinTypeGPIOOutput(PORT_4, PIN_1);

  Clock_Params clockParams;
  Error_Block eb;
  Error_init(&eb);
  Clock_Params_init(&clockParams);

  clockParams.period = brightness * PWM_QUANTA ;

  clockParams.startFlag = TRUE;
  myClock = Clock_create(myHandler1, 400, &clockParams, &eb);
  if (myClock == NULL)
  {
    System_abort("Clock create failed");
  }
}

void myHandler1(void)
{
  static int pin_state = 1 ;

  // Toggle pin state and timer period
  if( pin_state == 0 )
  {
    pin_sate = 1 ;
    Clock_setPeriod( myClock, brightness * PWM_QUANTA ) ;
  }
  else
  {
    pin_sate = 0 ;
    Clock_setPeriod( myClock, (255 - brightness) * PWM_QUANTA ) ;
  }

  // Set pin state
  GPIOPinWrite(PORT_4, PIN_1, pin_state) ;
}

用于在客户端下载文件的代码

{{1}}

1 个答案:

答案 0 :(得分:0)

为了让服务器接受另一个(和更多)连接,你必须将它放入一个循环

while(someConditionIndicatingYourServerShouldRun) {
   Socker socket = serverSocket.accept();
   //respond to the client

}

我建议使用线程池并将处理提交给线程池,即使用ExecutorService。此外,您应该在完成后关闭资源,例如流,&#34;尝试使用资源&#34;构造可以帮助你。所以你的代码可能看起来像这样

ServerSocket serverSocket =  ...;
ExecutorService threadPool = Executors.newFixedThreadPool(10);
AtomicBoolean running = new AtomicBoolean(true);
while(running.get()) {
  Socket socket = serverSocket.accept();
  threadPool.submit(() -> {
    try(ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
        OutputStream os = new ObjectOutputStream(socket.getOutputStream())) {
        String command = is.readUTF();
        if("shutdown".equals(command)) {
          running.set(false);
        } else {
          this.statusBox.setText("Received message from Client: " + command);    
        }   
    } catch (IOException e) {
      e.printStackTrace();
    }
  });
}