Home > Java > javaTutorial > Sharing examples of Socket programming in Java (picture)

Sharing examples of Socket programming in Java (picture)

黄舟
Release: 2017-05-28 09:20:36
Original
2227 people have browsed it

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

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

多线程的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();
    }
  }
}
Copy after login

当然这里的重点在于如何实现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();
      }
    }
  }
}
Copy after login

当然是先多线程还有其它的方式,譬如线程池,或者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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template