日期:2014-05-20  浏览次数:20944 次

大家下,socket编程如何关闭输入输出流?
问题是,我按照一般写法,所有输入流,输出流在操作完毕后,就直接给close了,但是就会报错。如果不都给close掉,程序还正常的
服务端代码:
Java code
public class Server2 extends Thread {
    Socket socket;
    public Server2(Socket socket, String uuid) {
        super(uuid);
        this.socket = socket;
    }
    @Override
    public void run() {
        System.out.println("running..");
        try {
            this.readSocket();
            this.writeSocket();
        } catch (Exception ioe) {
            ioe.printStackTrace();
        } finally {
            this.closeSocket();
        }
    }
    /**
     * 将response信息发送到socket客户端
     * 
     * @param response
     */
    private void readSocket() {
        try {
            InputStream ins = socket.getInputStream();
            DataInputStream dins = new DataInputStream(ins);
            byte[] size = new byte[10];
            dins.read(size);
            System.out.println("size is "+new String(size));
            byte[] xml = new byte[Integer.parseInt(new String(size))];
            dins.readFully(xml);
            System.out.println("xml is "+new String(xml));
            ins.close();
            dins.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 将response信息发送到socket客户端
     * 
     * @param response
     */
    private void writeSocket() {
        try {
            OutputStream outs = socket.getOutputStream();
            DataOutputStream douts = new DataOutputStream(outs);
            byte[] b = this.compress();
            DecimalFormat format=new DecimalFormat("0000000000");   
            String size = format.format(b.length);
            douts.write(size.getBytes());
            douts.write(b);
            douts.flush();
            douts.close();
            outs.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private byte[] compress() {
        String xml = "<aa><bb>测试xml</bb></aa>";
        return GZip.compress(xml.getBytes());
    }
    
    /**
     * 一个线程处理完后,关闭socket连接
     */
    public void closeSocket() {
        try {
            this.socket.close();
        } catch (IOException e) {
            System.out.println("关闭socket异常");
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        ExecutorService exService = Executors.newFixedThreadPool(30);
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(9999);
            System.out.println("服务成功启动了!");
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (true) {
            try {
                Socket socket = serverSocket.accept();
                socket.setSoLinger(true, 3600); //未发送完全的数据可以再等3600秒才关闭底层socket    
                System.out.println("接收到一个客户端请求!");
                UUID uuid = UUID.randomUUID();
                Server2 sp = new Server2(socket, uuid.toString());
                exService.execute(sp);
                //sp.start();
                //sp.join();// 主线程要等待该线程终止。
            } catch (Exception ne) {
                ne.printStackTrace();
            }
        }
    }
}

客户端代码
Java code

public class SocketClient2 extends Thread {
    static int count=0;
    @Override
    public void run() {
        try {
                byte[] ww = "<root></root>".getBytes();
                Socket socket = new Socket("localhost",9999);    
                socket.setSoTimeout(2*60*1000);
                OutputStream outs = socket.getOutputStream();
                DecimalFormat format=new DecimalFormat("0000000000");   
                String size = format.format(ww.length);
                //用来通知长度的报文头
                outs.write(size.getBytes());7.HibernateTemplate.execute(HibernateTemplate.java:372)
    at org.springframework.orm.hibernate3.HibernateTemplate.load(HibernateTemplate.java:502)
    at org.springframework.orm.hibernate3.HibernateTemplate.load(HibernateTemplate.java:496)
    at com.baidu.manageSystem.machineRoom.dao.EmployeeDao.deleteById(EmployeeDao.java:157)
    at com.baidu.manageSystem.machineRoom.controller.EmployeeAction.deleteById(EmployeeAction.java:313)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270)
    at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187)
    at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
    at com.baidu.manageSystem.common.filter.EncodingFilter.doFilter(EncodingFilter.java:32)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:875)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
    at java.lang.Thread.run(Thread.java:619)