search
HomeJavaJavaBaseJava determines whether the socket is connected

Java determines whether the socket is connected

There is a method sendUrgentData in the socket class, which will send one byte of data to the output stream. As long as the SO_OOBINLINE attribute of the other party's Socket is not turned on, this byte will be automatically discarded ( In Java, an exception is thrown), and the SO_OOBINLINE attribute is turned off by default. Recommended: java video tutorial

Example:

public class Nksocket extends Thread{ 
public String ip=null;//连接服务器的IP 
public Integer port=null;//连接服务器的端口 
private Socket socket=null;//套节字对象 
private boolean close = false; // 关闭连接标志位,true表示关闭,false表示连接 
private Integer sotimeout=1*1*10;//超时时间,以毫秒为单位 
//------------------------------------------------------------------------------ 
public Nksocket(){ 
   init(); 
} 
public Nksocket(String ip,Integer port){ 
   setIp(ip); 
   setPort(port); 
   init(); 
} 
/**
* 初始化socket对象
*/ 
public void init(){ 
   try { 
    InetAddress address = InetAddress.getByName(getIp()); 
    socket = new Socket(address,getPort()); 
    socket.setKeepAlive(true);//开启保持活动状态的套接字 
    socket.setSoTimeout(sotimeout);//设置超时时间 
    close=!Send(socket,"2");//发送初始数据,发送成功则表示已经连接上,发送失败表示已经断开 
   }catch(UnknownHostException e) { 
    e.printStackTrace(); 
   }catch(IOException e){ 
    e.printStackTrace(); 
   } 
} 
/**
* 读数据线程
*/ 
public void run() { 
   while(true){ 
    //---------读数据--------------------------- 
    close = isServerClose(socket);//判断是否断开 
    if(!close){//没有断开,开始读数据 
     String readtext = ReadText(socket); 
     if(readtext!=null && readtext.trim().length()>0){ 
      System.out.println("读取数据:"+readtext); 
     } 
    } 
    //---------创建连接------------------------- 
    while(close){//已经断开,重新建立连接 
     try{ 
      System.out.println("重新建立连接:"+getIp()+":"+getPort()); 
      InetAddress address = InetAddress.getByName(getIp()); 
      socket = new Socket(address,getPort()); 
      socket.setKeepAlive(true); 
      socket.setSoTimeout(sotimeout); 
      close = !Send(socket,"2"); 
      System.out.println("建立连接成功:"+getIp()+":"+getPort()); 
     }catch(Exception se){ 
      System.out.println("创建连接失败:"+getIp()+":"+getPort()); 
      close=true; 
     } 
    } 
   } 
} 
/**
* 发送数据,发送失败返回false,发送成功返回true
* @param csocket
* @param message
* @return
*/ 
public Boolean Send(Socket csocket,String message){ 
   try{ 
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true); 
    out.println(message); 
    return true; 
   }catch(Exception se){ 
    se.printStackTrace(); 
    return false; 
   } 
} 
/**
* 读取数据,返回字符串类型
* @param csocket
* @return
*/ 
public String ReadText(Socket csocket){ 
   try{ 
    csocket.setSoTimeout(sotimeout); 
    InputStream input = csocket.getInputStream(); 
    BufferedReader in = new BufferedReader(new InputStreamReader(input)); 
    char[] sn = new char[1000]; 
    in.read(sn); 
    String sc = new String(sn); 
    return sc; 
   }catch(IOException se){ 
    return null; 
   } 
} 
/**
* 判断是否断开连接,断开返回true,没有返回false
* @param socket
* @return
*/ 
public Boolean isServerClose(Socket socket){ 
   try{ 
    socket.sendUrgentData(0xFF);//发送1个字节的紧急数据,默认情况下,服务器端没有开启紧急数据处理,不影响正常通信 
    return false; 
   }catch(Exception se){ 
    return true; 
   } 
} 
/**
* 测试
* @param ags
*/ 
public static void main(String[] ags){ 
   Nksocket nksocket = new Nksocket("127.0.0.1",8090); 
   nksocket.start(); 
} 
//------------------------------------------------------------------------------ 
public String getIp() { 
   return ip; 
} 
public void setIp(String ip) { 
   this.ip = ip; 
} 
public Integer getPort() { 
   return port; 
} 
public void setPort(Integer port) { 
   this.port = port; 
} 
}

For more java knowledge, please pay attention to the java basic tutorial column on the PHP Chinese website.

The above is the detailed content of Java determines whether the socket is connected. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor