search
HomeJavajavaTutorialSharing examples of Socket programming in Java (picture)

Sharing examples of Socket programming in Java (picture)

May 28, 2017 am 09:20 AM
javasocketprogramming

Socket is very practical for us. Below are the notes for this study. It is mainly divided into exception types, interaction principles, Socket, ServerSocket, and multi-threading.

For real-time applications or real-time games, the HTTP protocol often cannot meet our needs. At this time, Socket is very practical for us. Below are the notes for this study. It is mainly explained in terms of exception types, interaction principles, Socket, ServerSocket, and multi-threading.

Exception types

Before understanding the contents of Socket, you must first understand some of the exception types involved. The following four types all inherit from IOException, so many of them can pop up IOException directly.

UnkownHostException:   Host name or IP error
ConnectException:   The server refused the connection, the server did not start, (the number of queues was exceeded, the connection was refused)
SocketTimeoutException:   Connection timeout
BindException:   The Socket object cannot be connected to The specified local IP address or port binding

Interaction process

Interaction between Socket and ServerSocket, I think the following picture has been It was very detailed and clear.

Socket constructor

Socket()
Socket(InetAddress address, int port)throws UnknownHostException, IOException
Socket(InetAddress address, int port, InetAddress localAddress, int localPort)throws IOException
Socket(String host, int port)throws UnknownHostException, IOException
Socket(String host, int port, InetAddress localAddress, int localPort)throws IOException

Except the first one without parameters, other constructors will try to establish a connection with the server. If it fails, an IOException error will be thrown. If successful, the Socket object is returned.

InetAddress is a class used to record hosts. Its static getHostByName(String msg) can return an instance. Its static method getLocalHost() can also obtain the IP address of the current host and return an instance. The parameters of the Socket(String host, int port, InetAddress localAddress, int localPort) constructor are target IP, target port, bound local IP, and bound local port respectively.

Socket method

getInetAddress(); The IP address of the remote server
getPort(); The port of the remote server
getLocalAddress()  The IP address of the local client
getLocalPort()  The port of the local client
getInputStream();  Get the input stream
getOutStream();  Get the output stream

It is worth noting that , among these methods, the most important ones are getInputStream() and getOutputStream().

Socket status

isClosed(); //Whether the connection has been closed, if closed, return true; otherwise, return false
isConnect(); //If it has been connected before, return true; otherwise, return false
isBound(); //If the Socket has been bound to a local port, return true; otherwise, return false

If you want to confirm whether the Socket status is connected, the following statement is a good way to judge.

boolean isConnection=socket.isConnected() && !socket.isClosed(); // Determine whether the current connection is in progress

Half-closed Socket

Many times, we don’t know how long it will take to read in the obtained input stream before it ends. The following are some of the more common methods:

  •  Custom identifier (such as the following example, when receiving the "bye" string, close the Socket)

  •  Inform the read length (for some custom protocols, the first few bytes are fixed to indicate the read length)

  •  Read all Data

  •  When the Socket is closed when calling close, close its input and output streams

ServerSocket constructor


ServerSocket()throws IOException
ServerSocket(int port)throws IOException
ServerSocket(int port, int backlog)throws IOException
ServerSocket(int port, int backlog, InetAddress bindAddr)throws IOException

Note:

1. port service The port to be monitored by the client; the queue length of the backlog client connection request; bindAddr server binding IP

2. If the port is occupied or does not have permission to use certain ports, a BindException error will be thrown. For example, ports 1~1023 require administrators to have permission to bind.

3. If the port is set to 0, the system will automatically assign a port to it;

4. bindAddr用于绑定服务器IP,为什么会有这样的设置呢,譬如有些机器有多个网卡。

5. ServerSocket一旦绑定了监听端口,就无法更改。ServerSocket()可以实现在绑定端口前设置其他的参数。 

单线程的ServerSocket例子 


public void service(){
  while(true){
    Socket socket=null;
    try{
      socket=serverSocket.accept();//从连接队列中取出一个连接,如果没有则等待
      System.out.println("新增连接:"+socket.getInetAddress()+":"+socket.getPort());
      ...//接收和发送数据
    }catch(IOException e){e.printStackTrace();}finally{
      try{
        if(socket!=null) socket.close();//与一个客户端通信结束后,要关闭Socket
      }catch(IOException e){e.printStackTrace();}
    }
  }
}

多线程的ServerSocket

多线程的好处不用多说,而且大多数的场景都是多线程的,无论是我们的即时类游戏还是IM,多线程的需求都是必须的。下面说说实现方式:

  •  主线程会循环执行ServerSocket.accept();

  •  当拿到客户端连接请求的时候,就会将Socket对象传递给多线程,让多线程去执行具体的操作;

实现多线程的方法要么继承Thread类,要么实现Runnable接口。当然也可以使用线程池,但实现的本质都是差不多的。

这里举例:

下面代码为服务器的主线程。为每个客户分配一个工作线程:


public void service(){
  while(true){
    Socket socket=null;
    try{
      socket=serverSocket.accept();            //主线程获取客户端连接
      Thread workThread=new Thread(new Handler(socket));  //创建线程
      workThread.start();                  //启动线程
    }catch(Exception e){
      e.printStackTrace();
    }
  }
}

当然这里的重点在于如何实现Handler这个类。Handler需要实现Runnable接口: 


class Handler implements Runnable{
  private Socket socket;
  public Handler(Socket socket){
    this.socket=socket;
  }
  
  public void run(){
    try{
      System.out.println("新连接:"+socket.getInetAddress()+":"+socket.getPort());
      Thread.sleep(10000);
    }catch(Exception e){e.printStackTrace();}finally{
      try{
        System.out.println("关闭连接:"+socket.getInetAddress()+":"+socket.getPort());
        if(socket!=null)socket.close();
      }catch(IOException e){
        e.printStackTrace();
      }
    }
  }
}

当然是先多线程还有其它的方式,譬如线程池,或者JVM自带的线程池都可以。这里就不说明了。

The above is the detailed content of Sharing examples of Socket programming in Java (picture). 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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software