Socket and ServerSocket Learning notes

Source: Internet
Author: User

For instant-class applications or instant-class games, the HTTP protocol is often not enough to meet our needs. This will be, the socket is very useful for us. Here are the notes for this study. The main sub-types of anomalies, interaction principles, sockets, ServerSocket, multi-threaded these aspects of the elaboration. Exception TypeBefore you understand the contents of the socket, you need to understand some of the exception types involved. The following four types are inherited from the IOException, so a lot of the direct pop-up ioexception can be. Unkownhostexception: Host name or IP error connectexception: Server refused connection, server did not start, (exceeded number of queues, refused connection) Sockettimeoutexception: Connection Timeout B Indexception:socket object cannot bind to a local IP address or port being established Interactive ProcessSocket and ServerSocket interaction, the following picture I think has been said in very detailed very clear. Socket constructor Function

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 type without parameters, Other constructors attempt to establish a connection to the server. If the failure throws a IOException error. If successful, the socket object is returned. InetAddress is a class used to record a 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) constructors are target IP, destination port, bound IP, bound port. Socket MethodGetinetaddress ();          The IP address of the remote server Getport (); Remote server Port getlocaladdress () local client IP address getlocalport () port of the local client getInputStream(); Get input stream Getoutstream(); Get output stream It's worth noting that the most important of these methods is getInputStream () and Getoutputstream (). Socket StatusIsClosed ();      If the connection is closed, returns true if closed, otherwise returns Falseisconnect ();            Returns True if ever connected, otherwise returns Falseisbound (); Returns true if the socket is already bound to a local port, otherwise false if you want to confirm that the state of the socket is in a connection, the following statement is a good way to judge.
Boolean isconnection=socket.isconnected () &&!socket.isclosed ();   // Determine if the connection is currently in 

half-closed socketmany times, we don't know how long it will be to end up in the input stream we get. Here are some of the more common approaches:
    • Custom identifiers (such as the following example, when a "bye" string is received, the socket is closed)
    • Tells the read length (some custom protocol, fixed the first few bytes to indicate the length of the Read)
    • Finish reading all the data
    • Closes the input and output stream when the socket closes when it calls close
  ServerSocket constructor FunctionServerSocket () throws IOExceptionserversocket (int port) throws IOExceptionserversocket (int port, int backlog) throws IOExceptionserversocket (int port, int backlog, inetaddress bindaddr) throws IOException Note the point:1. Ports to be monitored by Port server; Queue Length for backlog client connection requests; Bindaddr server-bound IP2. A bindexception error is thrown if the port is occupied or does not have permission to use certain ports. For example, 1~1023 ports require an administrator to have permission bindings. 3. If the set port is 0, then the system will automatically assign a port to it;4. Bindaddr is used to bind server IP, why is there such a setting, for example, some machines have multiple network cards. 5. ServerSocket cannot be changed once the listening port is bound. ServerSocket () can be used to set other parameters before the binding end.  ServerSocket example of a single thread
PublicvoidService () {WhileTrue) {Socket socket=Null;try{socket=serversocket.accept (); // Remove a connection from the connection queue, and if not, wait for System.out.println ("New Connection:" +socket.getinetaddress () + ":" +< Span style= "color: #000000;" >socket.getport ()); ... // receive and send data}catch ( IOException e) {e.printstacktrace ();} finally{try{if (Socket!=null) Socket.close (); //catch  (IOException e) {e.printstacktrace ();}} }} 

multi-threaded ServerSocketMulti-Threading benefits do not have to say, and most of the scenes are multi-threaded, whether it is our real-time game or IM, multi-threaded requirements are required. Let's talk about the implementation method:
    • The main thread will loop execution serversocket.accept ();
    • When the client connection request is received, the socket object will be passed to multi-threading, so that multi-threaded to perform the specific operation;
The method of implementing multithreading either inherits the thread class or implements the Runnable interface. Of course, the thread pool can be used, but the essence of implementation is almost the same. Here is an example: The following code is the main thread of the server. Assign a worker thread to each customer:
Publicvoid service () {while ( truetry{socket=serversocket.accept (); // 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 focus here, of course, is how to implement the Handler class. Handler needs to implement the Runnable interface:
Class HandlerImplementsrunnable{PrivateSocket socket;PublicHandler (socket socket) {this.socket=Socket }public void run () { Span style= "color: #0000ff;" >try{System.out.println ("New Connection:" +socket.getinetaddress () + ":" + socket.getport ()); Thread.Sleep (10000catch (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 ();}}}   

There are, of course, multithreading and other ways, such as the thread pool, or the thread pool that the JVM comes with. There is no explanation here.

Socket and ServerSocket Learning notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.