zoukankan      html  css  js  c++  java
  • 关闭socket以及Socket选项

    1 关闭socket

      ·1)socket套接字使用完毕之后,我们需要将起及时的关闭,正如输入输出流的关闭是一样的;在我上一篇文章中介绍了如何模拟httpClient发送请求数据;这里我还是使用上一篇文章中的代码做一个socket的关闭操作;我们一般是将socket放在finally{}代码块中去执行的,因为这部分总归是要执行的。

     public void communicate() throws Exception {
            try{
                StringBuffer sb = new StringBuffer("GET " + "/leoshop/AboutBlank.jsp" + " HTTP/1.1
    ");
                sb.append("Host: localhost:8080
    ");
                sb.append("Accept: */*
    ");
                sb.append("Accept-Language: zh-cn
    ");
                sb.append("Accept-Encoding: gzip, deflate
    ");
                sb.append("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 10.0)
    ");
                sb.append("Connection: Keep-Alive
    
    ");
    
                //发出HTTP请求
                OutputStream socketOut = socket.getOutputStream();
                socketOut.write(sb.toString().getBytes());
                socket.shutdownOutput();  //关闭输出流
    
                InputStream socketIn = socket.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(socketIn, "UTF-8"));
                String data;
                while ((data = br.readLine()) != null) {
                    System.out.println(data);
                }
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                try {
                    //socket套接字的关闭
                    if(socket!=null) socket.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    1. socket以下的三个方法
      1. boolean closed = socket.isClosed();  //判断是否关闭socket,true表示关闭,false表示没有关闭;
        boolean connected = socket.isConnected(); //判断是否和远程主机连接,true表示连接,false表示没有。
        boolean bound = socket.isBound();  //判断该socket是否已经绑定了本地的端口,true表示绑定,flase表示没有

     

  • 相关阅读:
    多线程 C#解决方案小结
    程序员的灯下黑:Handson,Handson,Handson!
    有一家银行每天早上都在你的帐户里存入86,400
    3D流水线[引用]
    诸葛亮著作
    Vista 用户头像存储路径
    C# 关闭显示器的函数
    程序员的灯下黑:管理还是技术?兴趣优先
    VS1.4挤房+MH的登陆器
    失眠的调养
  • 原文地址:https://www.cnblogs.com/gosaint/p/8283169.html
Copyright © 2011-2022 走看看