Как закрыть SerialPort, если клиент закрывает Soket

Рейтинг: 0Ответов: 1Опубликовано: 30.06.2011

Ситуация вот какая: клиент и сервер общаются через сокет. Сервер с модемом через SerialPort. И сокет и сериал-Порт имеют свои Input- и OutputStream. На сервере я читаю из сокетного InputStream и засовываю это в OutputStream сериал-Порта. Когда клиент у себя делает socket.close(), как серверу в ответ на это закрыть SerialPort? Спасибо.

package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import gnu.io.*;

public class ClientConnection implements Runnable {
    private SerialPort port = null;
    private Socket client;
    private InputStream serialPortInputStream;
    private OutputStream serialPortOutputStream;
    private InputStream clientInputStream;
    private OutputStream clientOutputStream;
    private boolean isStopWork = false;

    public ClientConnection(Socket client) {
        this.client = client; 
    }

    public void run() {        
        try {
            port = ModemManager.getFreePort();
        }
        catch (PortInUseException e) {
            e.printStackTrace();
        }
        try {
            clientInputStream = client.getInputStream();
            clientOutputStream = client.getOutputStream();
            serialPortInputStream = port.getInputStream();
            serialPortOutputStream = port.getOutputStream();

            byte[] clientBuffer = new byte[512];
            byte[] serialPortBuffer = new byte[512];
            int readFromSerial;
            int readFromClient;

            readFromClient = clientInputStream.read(clientBuffer);
            serialPortOutputStream.write(clientBuffer, 0, readFromClient);
            while ((readFromSerial = serialPortInputStream.read(serialPortBuffer)) != -1) {
                try {
                    readFromClient = clientInputStream.read(clientBuffer);
                }
                catch (Exception e) {
                    port.close();
                }
                clientOutputStream.write(serialPortBuffer, 0, readFromSerial);
            }

        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                clientInputStream.close();
                clientOutputStream.close();
                serialPortInputStream.close();
                serialPortOutputStream.close();
                port.close();
                client.close();
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Ответы

Ответов пока нет.