0

我又带着另一个问题回来了,我尝试寻找一个问题/答案,但到目前为止它们都没有奏效,所以我决定再发布一个。我在 Java/Tomcat 中运行了一个小型 REST JAXRS WebService,我希望从 JSP 页面发送命令来启动和停止 Socket 客户端。到目前为止,我实现了启动套接字,但我无法停止它,我做错了什么?

编辑 1: 我使用带有两个按钮的 JFrame 接口测试了相同的套接字功能(使用相同的类 PLC),一个连接代表 REST 功能,另一个断开连接,它可以工作

我的休息功能

NewTen_PLC m_plc = new NewTen_PLC(0x01, "Central Park", "10.80.4.10", 5001);
Thread m_thread;

@PUT
@Path("/connect")
public void Connect(InputStream is)
{       
    System.out.println("CONNECT COMMAND RECEIVED");
    try
    {
        System.out.println( "Starting Executor" );

        //Using thread manager
        //ExecutorService threadExecutor = Executors.newCachedThreadPool();
        //Start Thread
        //threadExecutor.execute(m_plc);            
        //Shutdown working threads when task is complete
        //threadExecutor.shutdown();

        //Using Thread
        m_thread = new Thread(m_plc);
        m_thread.start();

        System.out.println( "Tasks started, main ends.\n" );
    }
    catch(Exception ex)
    {

    }       
}

@PUT
@Path("/disconnect")
public void Disconnect(InputStream is)
{
    System.out.println("DISCONNECT COMMAND RECEIVED");

    try
    {           
        //m_plc.closeConnection();          
                    m_plc.m_bConnected = false;
    }
    catch(Exception ex)
    {
        System.out.println("Error while trying to close socket");
        ex.printStackTrace();
    }       
}

这是包含 Socket 函数和线程 Run 方法的 PLC 类。

//--------------------------------------------------------------------------------------------------------
// Run (Thread)
//--------------------------------------------------------------------------------------------------------
@Override
public void run()
{
    try
    {
        //DEBUG
        System.out.printf("\n Thread Started and Running in %s \n", getPLCName());
        //Connect to remote site
        connectToRemoteServer();
        //Set streams
        getStreams();
        //Process connection
        processConnection();
    }
    catch(EOFException eofException)
    {
        System.out.println( "\nClient terminated connection" );     
    }
    catch(IOException ioException)
    {
        ioException.printStackTrace();      
    }
    finally
    {
        closeConnection(); // close connection      
    }
}   
//--------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------
// Connect to Server/Remote Site
//--------------------------------------------------------------------------------------------------------
private void connectToRemoteServer() throws IOException
{
    //DEBUG
    System.out.println("Attempting connection to site");

    //Get IP Address
    InetAddress ipAddress = InetAddress.getByName(this.getIPAddress());
    //Create and Open Socket to server
    m_clientSocket = new Socket(ipAddress, this.getPort(), null, this.getLocalPort());
    //Set connected
    if(m_clientSocket != null)
        m_bConnected = true;
    //Set read timeout to infinite
    m_clientSocket.setSoTimeout(0);

    //DEBUG
    System.out.println("Connected to site");
}
//--------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------
// Get in and out Streams
//--------------------------------------------------------------------------------------------------------
private void getStreams() throws IOException
{
    //DEBUG
    System.out.println("Setting Streams");

    //Input data stream
    m_inStream = new DataInputStream(m_clientSocket.getInputStream());
    //Output data stream
    m_outStream = new DataOutputStream(m_clientSocket.getOutputStream());
}
//--------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------
// Process connection
//--------------------------------------------------------------------------------------------------------
private void processConnection() throws IOException
{
    NewTen_Buffer inBuffer = new NewTen_Buffer(8192);

    try // read message and display it
    {
        while(m_inStream.read() != -1 && m_bConnected == true)      
        {
            //Read 
            inBuffer.m_iSize = m_inStream.read(inBuffer.m_bBuffer);
            //DEBUG                  
            System.out.printf("Data read has %d bytes \n", inBuffer.m_iSize);

            //Decode
            newData(inBuffer);
        }   
            //DEBUG
        System.out.println("OUT OF READING LOOP");  
    } 
    finally
    {

    }
}
//--------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------
// Close Connection
//--------------------------------------------------------------------------------------------------------
public void closeConnection()
{
    System.out.println( "\nClosing connection" );
    try
    {   
        System.out.println( "\nIn Try closing" );
        m_bConnected = false;
        m_clientSocket.close(); // close socket         
        //System.out.println( "\nClosing Data input streams" );
        //m_inStream.close(); // close output stream
        //m_outStream.close(); // close input stream
        //System.out.println( "\nShutdown ip op" );
        //m_clientSocket.shutdownInput();
        //m_clientSocket.shutdownOutput();
        //System.out.println( "\nClosing socket" );
        //m_clientSocket.close(); // close socket
        System.out.println( "\nEnd of Try closing" );
    }
    catch ( IOException ioException )
    {
        ioException.printStackTrace();
    } // end catch      
}
//--------------------------------------------------------------------------------------------------------  

任何建议如何阻止它?

干杯,狮子座

4

1 回答 1

0

我还没有完全阅读所有服务器代码,但我猜你的服务器线程阻塞等待来自流的连接/输入,因此你无法停止它。

如果你必须使用 REST,你可以强制终止线程来停止它(我不能保证暗示)。或者其他方法是实现一个套接字协议来停止服务器——而不是使用 REST

于 2013-04-09T07:31:07.157 回答