For real-time applications or real-time games, the HTTP protocol often cannot meet our needs. Socket is very practical for us. Below are notes for this study. It mainly explains the aspects of exception type, interaction principle, Socket, ServerSocket, and multithreading.
Exception type
Before understanding the content of Socket, you need to understand some exception types involved. The following four types are all inherited from IOException, so many IOException pop up directly afterwards.
UnkownHostException: Host name or IP error
ConnectException: The server refuses to connect, the server does not start, (the number of queues exceeds, connection is rejected)
SocketTimeoutException: Connection timeout
BindException: Socket object cannot be bound to the formulated local IP address or port
Interaction process
I think the following picture has been explained in detail and clearly.
Socket
Constructor
Socket()Socket(InetAddress address, int port)throws UnknownHostException, IOExceptionSocket(InetAddress address, int port, InetAddress localAddress, int localPort)throws IOExceptionSocket(String host, int port)throws UnknownHostException, IOExceptionSocket(String host, int port, InetAddress localAddress, int localPort)throws IOException
Except for the first without parameters, other constructors will try to establish a connection to 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 the host. Its static getHostByName(String msg) can return an instance, and 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 the target IP, the target port, the local IP, and the local port.
Socket method
getInetAddress(); IP address of the remote server
getPort(); port of remote server
getLocalAddress() IP address of the local client
getLocalPort() port of local client
getInputStream(); getInputStream();
getOutStream(); get output stream
It is worth noting that among these methods, the most important ones are getInputStream() and getOutputStream().
Socket Status
isClosed(); //Is the connection closed? If closed, return true; otherwise, return false
isConnect(); //Return true if connected; 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's status is in a connection, the following statement is a good way to judge.
boolean isConnection=socket.isConnected() && !socket.isClosed(); //Judge whether it is currently in connection
Semi-closed Socket
Many times, we don't know how long it takes to finish in the obtained input stream. Here are some common methods:
ServerSocket
Constructor
ServerSocket()throws IOExceptionServerSocket(int port)throws IOExceptionServerSocket(int port, int backlog)throws IOExceptionServerSocket(int port, int backlog, InetAddress bindAddr)throws IOException
Note:
1. The port to be listened to by the port server; the queue length of the backlog client connection request; the bindAddr server binds the 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 from 1 to 1023 require an administrator to have permission binding.
3. If the port is set to 0, the system will automatically assign a port to it;
4. bindAddr is used to bind the server IP. Why is there such a setting? For example, some machines have multiple network cards.
5. Once the ServerSocket is bound to the listening port, it cannot be changed. ServerSocket() can set other parameters before binding the port.
Single-threaded ServerSocket example
public void service(){ while(true){ Socket socket=null; try{ socket=serverSocket.accept();//Take a connection from the connection queue, if not, wait for System.out.println("Address:"+socket.getInetAddress()+":"+socket.getPort()); ...//Receive and send data}catch(IOException e){e.printStackTrace();} finally{ try{ if(socket!=null) socket.close();//After communication with a client, close Socket }catch(IOException e){e.printStackTrace();} } }}Multithreaded ServerSocket
Needless to say, the benefits of multi-threading are multi-threading, and most scenarios are multi-threading. Whether it is our real-time games or IM, the multi-threading needs are necessary. Let’s talk about the implementation method below:
Methods that implement multi-threading either inherit the Thread class or implement the Runnable interface. Of course, thread pools can also be used, but the essence of implementation is similar.
Here is an example:
The following code is the main thread of the server. Assign a worker thread to each client:
public void service(){ while(true){ Socket socket=null; try{ socket=serverSocket.accept(); //The main thread gets the client connection Thread workThread=new Thread(new Handler(socket)); //Create thread workThread.start(); //Start thread}catch(Exception e){ e.printStackTrace(); } }}Of course, the focus here is on how to implement the Handler class. Handler needs to implement the Runnable interface:
class Handler implements Runnable{ private Socket socket; public Handler(Socket socket){ this.socket=socket; } public void run(){ try{ System.out.println("New connection:"+socket.getInetAddress()+":"+socket.getPort()); Thread.sleep(10000); }catch(Exception e){e.printStackTrace();} finally{ try{ System.out.println("Close the connection:"+socket.getInetAddress()+":"+socket.getPort()); if(socket!=null)socket.close(); }catch(IOException e){ e.printStackTrace(); } } }} Of course, there are other ways to multi-thread first, such as thread pools, or thread pools that are built into JVM. I won't explain it here.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.