This article briefly describes the java.net packet based on TCP/IP socket programming and its source code analysis
Write network programming This chapter, the original intention is to speak of HttpClient, Jetty, Netty use of experience, NiO and bio comparison, thrift and Avro, helpless today by the partners despise, he saw I used the Apache HttpClient (C) + Jetty (S), said: You are just passing some data, with the socket more simple and rapid, our amount of more than 10 T, no wonder my side of a bunch of timeout. Later he told me that he used the "C Call Linux Socket interface" to write his own library, very proud to express the speed of the lever (the project is a large quantity is a disadvantage), so I also looked at the java.net under the package of things, there will be two chapters, this chapter is to deal with TCP/IP socket part.
java.net includes the following categories: Datagransocket class, Socket/serversocket class, Inetxaddress class, URL-related class and others, this chapter is mainly about the socket/ ServerSocket Socket programming, nothing more than a socket (C) to connect a serversocket (S), so wrote two simple programs and analysis, features a dataacceptserver, You can create 4444 ports, can accept up to 50 connections, two Datasender, create long connections, and know how to send Byebye. For convenience, use UTF-8 character streams. The procedure is as follows://server Importjava.io.BufferedReader; Importjava.io.IOException; Importjava.io.InputStreamReader; Importjava.io.OutputStreamWriter; Importjava.io.PrintWriter; Importjava.net.ServerSocket; Importjava.net.Socket; Publicclass dataacceptserver { public static voidmain (String args[]) throws IOException {  ; serversocket server = null; Server =new serversocket (4444);/set server port &N Bsp socketsocket = null; int number= 0; Booleanflag = true; try{ &NB Sp while (flag) { & nbsp socket = server.accept ()//listening connection, method blocking, able to establish multiple long connections number++; Createhandlert Hread (Socket,number)//For each connection build thread &nbs P {finally{ &nbs P Server.close ();  / }
private static voidcreatehandlerthread (socket socket, int number) {Dataacceptserver das = new Dataacceptserv ER (); Handlerhandler = Das.new Handler (socket, number); Thread T =new thread (handler); T.start (); }
public class handlerimplements Runnable {privatesocket socket = null; Privateint number = 0;
Publichandler (socket socket, int number) {this.socket = socket; This.number = number; }
@Override Publ Icvoid run () { System.out.println ("Get the" Connetion withclient "+ number); bufferedreader in = null; printwriter out = null; try {  &NB Sp in = new BufferedReader (Newinputstreamreader ( &N bsp; &NBS p; Socket.getinputstream (), "UTF-8")); Get socket receive stream &NBsp out = new PrintWriter (newoutputstreamwriter  &NB Sp so Cket.getoutputstream (), "UTF-8"))//Get socket Send stream & nbsp; } catch (IOException e) { &nbs P e.printstacktrace (); } String getline = null; Boolean end = false; while (!end) { try {  &NB Sp getline =in.readline (); Get message } catch (IOException e) { e.printstacktrace (); &N Bsp break; } SYSTEM.OUT.PRINTLN (" GetMessage from Client "+ number +": " &N Bsp &nbsP + getline); out.write ("Ok\ n "); Back to OK Out.flus H (); if (getline.equ ALS ("Byebye")) {   ; End =true; } { try { &N bsp; In.close ();   out.close (); Socket.close () ; catch (IOException e) {  &NB Sp e.printstacktrace (); } System.out.println ("Release the connetion withclient" + number); }} ServerSocket class in java.net The main work (SocketImpl subclass Plainsocketimpl and its subclass Sockssocketimpl completes the most important work) First step: ServerSocket server = Newserversocket (4444) 1, converted to ServerSocket (int port, Intbacklog, InetaDdress bindaddr) Construction method, port (required) + Maximum number of connections (default 50) + service address (default native). The ip+ port is in the form of a inetsocketaddress class. 2, SecurityManager security =system.getsecuritymanager (), the security will check whether this port is available 3, bind (), Done by the native method Socketbind in Plainsocketimpl, that is, using system calls to complete the work of creating and binding ports 4, listen (), Done by the native method Socketlisten in Plainsocketimpl, that is, using system calls to complete setting the maximum number of connections, creating queuefor incoming connectionindications (A Request Toconnect), where the count parameter is the maximum number of connections. If Thequeue full of words, will be refuse behind the connection Step two: socket socket= server.accept (); 1, accept (Sockssocketimpl s), is a blocking method, Plainsocketimpl native method socketaccept to complete, that is, using system modulation to monitor whether there is a connection in, Until there is a connection 2, a response connection, create the socket object, and give it a very most wanted object Sockssocketimpl, it completes all the work that we see the socket object. Step three: Socket.getoutputstream () and Socket.getinputstream () to get the input and output stream of the Sockssocketimpl object. The next step is to use the flow to deal with the work.
Client Importjava.io.BufferedReader; Import java.io.IOException; Importjava.io.InputStreamReader; Importjava.io.OutputStreamWriter; Import Java.io.PrintWriter; Import Java.net.Socket; Importjava.net.UnknownHostException; public class Datasender { public static voidmain (String args[]) throwsunknownhostexception, &NB Sp IOException {  &N Bsp Socketsocket = new Socket ("127.0.0.1", 4444); Set server IP and port //socket.setsotimeout (10000);/Set timeout time & nbsp; bufferedreader sin = new BufferedReader (Newinputstreamreader ( system.in) printwriter out = new PrintWriter (Newoutputstreamwriter ( &NBsp; Socket.getoutputstream ( ), "UTF-8")//Get socket Send stream bufferedreader in = new BufferedReader ( Newinputstreamreader ( Socket.getinputstream (), "UTF-8"))//Get socket Receive stream Stringreadline = null; ReadLine =sin.readline (); while (!readline.equals ("Byebye")) {//Byebye terminating connection & nbsp out.println (ReadLine); Out.flush (); System.out.println ("Client:" +readline) ; System.out.println ("Server:" +in.readline ()); readline = Sin.readline ();  , out.close (); in.close (); socket.close ();  } The Socket class is simpler, but the secret behind it is also worth digging, and he does it primarily by creating a connection to a service and transferring data or commands to the First step: Socketsocket = new Socket ("127.0.0.1", 4444); 1, first to create a Sockssocketimpl object 2, bind (), by the Plainsocketimpl in the native method socketbind to complete, That is, use system call to complete the work of binding port 3, connect (), by the Sockssocketimpl object of Connect to enter (because it involves security verification and a variety of different connect methods such as agents, etc.), Finally, it is done by Plainsocketimpl's Socketconnect, and also by using system calls to complete the work of Connect. Step Two: Socket.getoutputstream () and Socket.getinputstream () to get SockssocketimpThe input and output stream of the L object. The next step is to use the flow to deal with the work.
See here, in fact, the most core of the work of socket programming is not done by itself, but by using a non-Java method to complete, JNI call System C library (will be introduced after the charter), so I think, within the scope of tolerance, slow is not Java fault, but I realized that there are problems. Finally, summarize a picture:
Because Bo Master knowledge is limited, if wrong, please correct comments, welcome to Exchange
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.