For real-time class applications or instant-class games, HTTP protocols are often not satisfied with our needs. This will, the socket is very useful for us. Here are the notes for this study. The main types of abnormal type, interaction principle, Socket, ServerSocket, multithreading in these aspects elaborated.
Exception type
Before you know the contents of the socket, you need to know some of the exception types involved. The following four types are inherited from the IOException, so a lot of direct pop-up ioexception can be.
Unkownhostexception: Host name or IP error
Connectexception: Server refused connection, server did not start, (exceeded queue number, refused connection)
Sockettimeoutexception: Connection Timeout
Bindexception:socket object cannot be bound to a set local IP address or port
Interaction process
Socket and ServerSocket interaction, the following picture I think has been said in detail very clear.
Socket
Constructors
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 Unk Nownhostexception, IOException
Socket (String host, int port, inetaddress localaddress, int localport) throws IOException
Except for the first without parameters, other constructors attempt to establish a connection to the server. If the failure will throw a ioexception error. If successful, the socket object is returned.
InetAddress is a class for recording hosts whose 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 arguments for the constructor of the Socket (String host, int port, inetaddress localaddress, int localport) are the destination IP, destination port, binding IP, binding to the port.
Socket method
Getinetaddress (); IP address of remote service side
Getport (); Ports on the remote service side
getlocaladdress () IP address of local client
Getlocalport () port for local client
getInputStream (); Get input stream
Getoutstream (); Get output stream
It is noteworthy that, in these methods, the most important is getinputstream () and Getoutputstream ().
Socket status
IsClosed (); Whether the connection is turned off, returns true if it is closed, otherwise returns false
Isconnect (); Returns true if the connection was ever connected; false otherwise
Isbound (); Returns true if the socket is already bound to a local port; false otherwise
The following statement is a good way of judging if you want to confirm that the socket is in a connected state.
Boolean isconnection=socket.isconnected () &&!socket.isclosed (); Determine whether you are currently connected
Semi-close socket
Most of the time, we don't know exactly how long it will be to get the input stream to finish. Here are some of the more common approaches:
- Custom identifiers (such as the following example, close the socket when the "Bye" string is received)
- Tells the read length (some of the custom protocols, fixed the first few bytes to indicate the length of the Read)
- After reading all the data
- Turn off the input and output stream when the socket is closed when it calls Close
ServerSocket
Constructors
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 the point:
1. Ports to be monitored by port server; Backlog the queue length of client connection requests; Bindaddr server-side binding IP
2. If the port is occupied or does not have permission to use certain ports, a bindexception error is thrown. For example, a 1~1023 port requires an administrator to have permission bindings.
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 there are such settings, such as some machines have more than one network card.
5. ServerSocket cannot be changed once the listening port is bound. ServerSocket () enables you to set additional parameters before the binding end.
ServerSocket example of a single thread
public void Service () {while
(true) {
Socket socket=null;
try{
socket=serversocket.accept ()//Remove a connection from the connection queue and wait for System.out.println if not
("New connection:" + 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 closes the socket
}catch (IOException e) { E.printstacktrace ();}}}
Multi-threaded ServerSocket
Multithreading benefits Needless to say, and most of the scenes are multi-threaded, whether our real-time game or IM, multithreading needs are necessary. Here's how to implement it:
- The main thread loops through the execution of Serversocket.accept ();
- When the client connection request is received, the socket object will be passed to the multithreading, so that multi-threaded to carry out the specific operation;
The method of implementing multithreading either inherits the thread class or implements the Runnable interface. Of course, you can use a thread pool, but the essence of implementation is the same.
Here are some examples:
The following code is the main thread of the server. Assign a worker thread to each customer:
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 ();
}
}
}
The point here, of course, is 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 connection:" +socket.getinetaddress () + ":" +socket.getport ());
if (socket!=null) socket.close ();
} catch (IOException e) {
e.printstacktrace ();}}}
Of course, there are other ways of multithreading, such as thread pooling, or the JVM's own thread pool. Here is not to say.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.