Java Socket Programming----communication is so refined

Source: Internet
Author: User
Tags readline

Http://www.cnblogs.com/rocomp/p/4790340.html

Java was originally introduced as a network programming language, which provides a high degree of support to the network, which makes the communication between client and server become reality, and in network programming, the socket is the most used. Like everyone familiar with the QQ, MSN has used the socket-related technology. Now let's uncover the mystery of the socket.

Socket Programming Basic knowledge of network (refer to computer network) about the computer network section can refer to related blog: theTCP/IP protocol stack and OSI reference Model detailed "http://wangdy.blog.51cto.com/3845563/1588379 1. The following three conditions are required for communication between two computers: IP Address, agreements, Port number 2. TCP/IP protocol: is the most widely used protocol in the world, it is a collection of multiple protocols on different levels based on TCP and IP, and it is also a family, or TCP/IP protocol stack tcp:transmission Control Protocol Transmission Protocol ip:internet Protocol Internet Protocol 3. TCP/IP five layer model Application layer: HTTP, FTP, SMTP, Telnet, etc. Transport Layer: TCP/IP Network layer: Data Link layer: Physical layer: Network cable, twisted pair, network card, etc. 4. IP address to enable communication between different computers in the network, each computer must have a unique identity---IP address. 32-bit binary 5. Port differentiate between multiple applications for a single host with a port number range of 0-65535, where 0-1023 bits are reserved for the system. such as: http:80 ftp:21 telnet:23 The IP address + port number makes up the so-called Socket,socket is the endpoint of a two-way communication link between programs running on the network and is the basis for TCP and UDP 6. Socket Socket: A combination of IP addresses and ports that have a unique identity on the network can form a uniquely identifiable identifier socket. socket principle mechanism: sockets on both ends of the communication network communication is actually the communication between sockets data is transmitted via IO between two sockets        7. Network support in Java for different levels of network communication, Java provides different APIs, which provide four main types of network functionality: inetaddress: Used to identify hardware resources on the network, primarily IP addresses URL: A Uniform Resource locator that allows you to read or write data directly on the network through a URL Sockets: Network communication using the TCP protocol socket-related classes Datagram: Using the UDP protocol, the data is stored in the user datagram and communicated over the network. Second, 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");

third, the URL class 1, URL (Uniform Resource Locator) Uniform Resource Locator, representing the address of a resource on the Internet, protocol name: resource Name        
    1. 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 content The 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. 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 ();

four, TCP programming 1, 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 lower 2. The class of network communication based on TCP protocol in Java Socket class for client Server-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 socket 4. Server side: ① Creating ServerSocket objects, binding listening ports ② listening for client requests via the Accept () method after 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. 1/** 2  * Socket communication based on TCP protocol, user login, server 3 */4//1, create a client socket, i.e. ServerSocket, specify the bound port, and listen to this port 5 ServerSocket ServerSocket =newserversocket (10086); a port of//1024-65535 6//2, call the Accept () method to start listening, waiting for 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 to after 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. 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}
five, UDP programming UDP Protocol (User Datagram Protocol) is non-connected, unreliable, unordered, fast In 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 out Datagrampacket class: Represents a datagram package Datagramsocket class: Classes for end-to-end communication 1, server-side implementation steps ① Create Datagramsocket, specify port number ② Creating Datagrampacket ③ Accept data sent by the client ④ reading Data
    1.  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. 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 ();

      Six, 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 situation 2. 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 directly 3. Transferring objects using TCP communication, serialization part of IO 4. Socket program transfer file, IO stream part    



From for notes (Wiz)

Java Socket Programming----communication is so refined

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.