Source: http://www.cnblogs.com/rocomp/p/4790340.html
A socket is a network-driven layer that is provided to the application programming interface and a mechanism. The socket can be likened to a port, the application as long as the goods are placed in the port, even if the delivery of goods completed. For the receiver application also create a port, just wait for the goods to arrive at the dock after the goods are taken away.
InetAddress
The inetaddress class identifies the hardware resource on the network and identifies the Internet Protocol (IP) address. There is no construction method for this class
1//Get native InetAddress instance 2 inetaddress address =inetaddress.getlocalhost (); 3 address.gethostname ();//Get Computer name 4 Address.gethostaddress ();//Gets the IP address 5 byte[] bytes = address.getaddress ();//Gets the IP address in the form of a byte array, four parts separated by dots 6 7// Get inetaddress instances of other hosts 8 inetaddress address2 =inetaddress.getbyname ("Other host Names"); 9 inetaddress ADDRESS3 = Inetaddress.getbyname ("IP Address");
second, the URL class1, URL (Uniform Resource Locator) Uniform Resource Locator, representing the address of a resource on the Internet, protocol name: resource Name
-
1//Create an instance of URL 2 url Baidu =new url ("http://www.baidu.com"); 3 URL url =new url (Baidu, "/index.html?username=tom#test");//? Represents the parameter, #表示锚点 4 Url.getprotocol ();//Gets the Protocol 5 url.gethost ();//Gets host 6 url.getport ();//If no port number is specified, the default port is used differently depending on the protocol. At this point the return value of the Getport () method is-1 7 url.getpath ();//Gets the file path 8 url.getfile ();//filename, including file path + parameter 9 url.getref ();//relative path is the anchor, that is, the content after the # Number 10 Url.getquery ();//query string, or parameter
2. Use URL to read Web contentThe OpenStream () method of the URL object allows the input stream of the specified resource to be read or accessed through the stream on the Web page
-
1//Use URL to read Web page Content 2//Create a URL instance 3 URL url =new url ("http://www.baidu.com"); 4 InputStream is = Url.openstream ();//Gets the byte input stream of a resource through the OpenStream Method 5 InputStreamReader ISR =newinputstreamreader (IS, "UTF-8 ");//convert byte input stream to character input stream, if no encoding is specified, Chinese may garbled 6 BufferedReader BR =newbufferedreader (ISR);//Add buffer for character input stream, improve reading efficiency 7 String data = Br.readline ();//Read Data 8 while (Data!=null) {9 System.out.println (data);//Output data = Br.readerline ();}12 br.close (); Isr.colose (); Is.close ();
third, TCP programming1, TCP protocol is a connection-oriented, reliable, orderly, byte-stream transmission of data, through three handshake to establish a connection, to form a channel to transmit data, in the connection of a large number of data transmission, the efficiency will be slightly lower2. The class of network communication based on TCP protocol in JavaSocket class for clientServer-side ServerSocket class 3. Socket Communication Steps① creating ServerSocket and Sockets② Open the input/output stream connected to the socket③ read/write to socket according to Protocol④ Closing the input/output stream, closing the socket4. Server side:① Creating ServerSocket objects, binding listening ports② listening for client requests via the Accept () methodafter the ③ connection is established, read the request information sent by the client via the input stream④ sending accent information through the output flow to the client⑤ closing Related resources
-
1/** 2 * Socket communication based on TCP protocol for user login, Service Side 3 */4//1, create a server-side socket, that is, ServerSocket, specify the bound port, and listen to this port 5 serversocket serversocket =newserversocket (10086);// 1024-65535 of a Port 6//2, call the Accept () method to start listening, waiting for the client connection 7 Socket socket = serversocket.accept (); 8//3, get input stream, and read client information 9 InputStream is = Socket.getinputstream (); InputStreamReader ISR =newinputstreamreader (IS); 11 BufferedReader BR =newbufferedreader (ISR); String info =null;13 while ((Info=br.readline ())!=null) {14 System.out.println ("I am the server, client said:" +info);}16 socket.shutdowninput ();//Close input stream 17//4, get output stream, respond to client requests OutputStream OS = Socket.getoutputstream (); PrintWriter pw = new PrintWriter (OS); Pw.write ("Welcome!" "); Pw.flush (); 22 23 24//5, Close resources pw.close (); Os.close (); Br.close (); Isr.close (); Is.close (); (); Serversocket.close ();
5. Client:
① Create a socket object that indicates the address and port number of the server you want to connect toafter the ② connection is established, the request information is sent through the output stream to the server side③ getting the server response through the input stream④ Closing Response Resources
-
1//Client 2//1, create client socket, specify server address and port 3 socket socket =newsocket ("localhost", 10086); 4//2, get output stream, send information to server 5 outputstream OS = Socket.getoutputstream ();//Byte output stream 6 PrintWriter pw =newprintwriter (OS);// Wraps the output stream into a print stream 7 Pw.write ("username: admin; password: 123"); 8 Pw.flush (); 9 Socket.shutdownoutput (); 10//3, get input stream, and read server-side response information One inputstream is = Socket.getinputstream (); BufferedReader br = New BufferedReader (IS), InputStreamReader String info = null;14 while ((Info=br.readline ())!null) { System.out.println ("I am the client, the server says:" +info); 16}17 18//4, Close resources br.close (); Is.close (); Pw.close (); Os.close (); 23 Socket.close ();
6. Application of multi-thread to realize communication between server and multi-client
① Server-side Create ServerSocket, loop call accept () Wait for client connection② Client creates a socket and requests and server-side connections③ Server side to accept the cram request, create a socket to establish a dedicated connection with the customer④ Connect two Sockets dialog on a separate thread⑤ Server side continues to wait for new connections
1//server thread handling 2//and Socket 3 socket socket associated with this thread =null; 4//5 public serverthread (socket socket) {6 this.socket = socket; 7} 8 9 publicvoid Run () {10//server handling code 11}12 13//== ==========================================14//server code: ServerSocket serversocket =newserversocket (10086); Socket =NULL;17 int Count =0;//record number of clients (true) {socket = serverscoket.accept (); Serverthread Serverthread =new Serverthread (socket); serverthread.start (); count++;23 System.out.println ("Number of client connections:" +count); 24}
four, UDP programmingUDP Protocol (User Datagram Protocol) is non-connected, unreliable, unordered, fastIn the data transmission , the data to be transmitted is defined as a datagram (Datagram), the size is limited to 64k, in the datagram indicates the socket (host address and port number) that the data requests to reach, and then sends the datagram outDatagrampacket class: Represents a datagram packageDatagramsocket class: Classes for end-to-end communication1, server-side implementation steps① Create Datagramsocket, specify port number② Creating Datagrampacket③ Accept data sent by the client④ reading Data
-
1//server side, implement UDP-based user login 2//1, Create server-side Datagramsocket, specify Port 3 datagramsocket socket =new datagramsocket (10010); 4//2, create a datagram to accept data sent by the client 5 byte[] Data =newbyte[1024];//6 datagrampacket packet =newdatagrampacket (data,data.length); 7//3, accept the data sent by the client 8 socket.receive (packet);//This method will block 9//4, read data, and String info =newstring (data,o,data.length) before accepting datagrams; System.out.println ("I am the server, the client tells me" +info); 12 13 14//=========================================================15/ /response data to the client 16//1, define the address of the client, port number, data inetaddress addressing = Packet.getaddress (); int port = Packet.getport (); byte[] Data 2 = "Welcome to YOU!" ". Geybytes (); 20//2. Create a datagram that contains data about the response datagrampacket Packet2 = new Datagrampacket (data2,data2.length,address,port); 22//3, Response client Socket.send (PACKET2), 24//4, close Resource socket.close ();
2. Client implementation steps
① defining sending information② Create Datagrampacket that contains the information that will be sent③ Creating Datagramsocket④ sending Data
-
1//Client 2//1, define the server's address, port number, data 3, inetaddress address =inetaddress.getbyname ("localhost"); 4 int port = 10010; 5 byte[] data = "Username: admin; password: 123". GetBytes (); 6//2, create datagram, contains data sent 7 Datagrampacket packet = Newdatagrampacket (data,data,length,address,port); 8//3, create Datagramsocket object 9 datagramsocket socket =newdatagramsocket (); 10//4, send data to Server socket.send (packet); 12 13 14// Accepts server-side response Data 15//======================================16//1, creating datagrams for receiving server-side response data byte[] Data2 = new byte[1024];18 Datagrampacket Packet2 = new Datagrampacket (data2,data2.length), 19//2, receiving server response data (socket.receive); raply = new String (Data2,0,packet2.getlenth ()); System.out.println ("I am the client, the server says:" +reply); 23//4, close resource Socket.close ();
Five, attention issues:
1.Multi-Threading priority issues:according to the actual experience,appropriate reduction of priority, no side may have a program running low efficiency situation2. Whether to turn off the output stream and the input stream:for the same socket, if the output stream is turned off, the socket associated with the output stream will also be closed, so it is generally not possible to close the stream and close the socket directly3. Transferring objects using TCP communication, serialization part of IO4. Socket program transfer file, IO stream part
(RPM) Java socket programming