Home Java JavaBase Java determines whether the socket is connected

Java determines whether the socket is connected

Jan 14, 2020 pm 01:21 PM
java

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; 
} 
}
Copy after login

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 of this Website
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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles