Sharing examples of Socket programming in Java (picture)
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

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

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

C is an ideal choice for beginners to learn system programming. It contains the following components: header files, functions and main functions. A simple C program that can print "HelloWorld" needs a header file containing the standard input/output function declaration and uses the printf function in the main function to print. C programs can be compiled and run by using the GCC compiler. After you master the basics, you can move on to topics such as data types, functions, arrays, and file handling to become a proficient C programmer.

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

Getting Started with Python Programming Install Python: Download and install from the official website. HelloWorld!: Use print("HelloWorld!") to print the first line of code. Practical case: Calculate the area of a circle: Use π (3.14159) and the radius to calculate the area of the circle. Variables and data types: Use variables to store data. Data types in Python include integers, floating point numbers, strings, and Boolean values. Expressions and assignments: Use operators to connect variables, constants, and functions, and use the assignment operator (=) to assign values to variables. Control flow: if-else statement: execute different code blocks based on conditions, determine odd

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.
