Java Socket programming-communication is made in this way

Source: Internet
Author: User

Java Socket programming-communication is made in this way
Java was originally used as a network programming language. It provides high support for the network, making communication between the client and the server a reality. In network programming, the most commonly used is Socket. QQ and MSN are familiar with Socket-related technologies. Let's unveil the secrets of Socket. Socket programming I. Basic network knowledge (refer to computer networks) for more information about computer networks, see related blogs: http://wangdy.blog.51cto.com/3845563/1588379 1. Communication between two computers requires the following three conditions: IP address, protocol, Port Number 2, TCP/IP protocol: it is the most widely used protocol in the world. It is a set of multiple protocols at different levels based on TCP/IP, it is also a TCP/IP Protocol family, or TCP/IP Protocol stack. TCP: Transmission Control Protocol Transport Control Protocol IP: Internet Protocol 3. layer-5 TCP/IP Model Application Layer: HTTP, FTP, SMTP, Telnet, and other transmission layers: TCP/IP network layer: data link layer: Physical Layer: network cable, twisted pair wire, network card, etc. 4. IP addresses are used to implement communication between different computers in the network, each computer must have A Unique Identifier-IP address. 32-bit binary 5. The port distinguishes multiple applications of a host. The port number ranges from 0 to 65535, And the 0-bits are reserved by the system. For example: HTTP: 80 FTP: 21 Telnet: 23 IP address + port number constitute the so-called Socket, Socket is the end point of the two-way communication link between programs running on the network, is the basis of TCP and UDP 6. Socket: the IP addresses and ports with unique identifiers on the network can be combined to form a Socket with unique identifiers. Socket principle mechanism: both ends of the communication have Socket network communication. In fact, the communication data between sockets is transmitted through IO between two sockets. 7. The network in Java supports different layers of network communication, java provides different APIs, which provide four types of network functions: InetAddress: used to identify the hardware resources on the network, mainly IP Address URL: unified resource locator, you can use a URL to directly read or write data on the network. Sockets: Network Communication Socket-related class datams implemented using the TCP protocol. data is stored in user Datagram using the UDP protocol, communicate over the network. 2. The InetAddress class is used to identify the hardware resources on the network and the Internet Protocol (IP) address. This class has no Constructor

1 // obtain the InetAddress instance 2 InetAddress address = InetAddress of the local machine. getLocalHost (); 3 address. getHostName (); // obtain the computer name 4 address. getHostAddress (); // obtain the IP address 5 byte [] bytes = address. getAddress (); // obtain the IP address in the byte array format, which is separated by points. Part 6 7 // obtain the InetAddress instance 8 InetAddress address2 = InetAddress of other hosts. getByName ("Other host names"); 9 InetAddress address3 = InetAddress. getByName ("ip address ");

 

Iii. URL Class 1. URL (Uniform Resource Locator) indicates the address of a Resource on the Internet. Protocol name: Resource Name
1 // create a URL for instance 2 URL baidu = new URL ("http://www.baidu.com"); 3 URL url = new URL (baidu, "/index.html? Username = tom # test ");//? Parameter, # indicates the ANCHOR 4 url. getProtocol (); // get Protocol 5 url. getHost (); // get host 6 url. getPort (); // if no port is specified, use the default port according to the protocol. The returned value of the getPort () method is-1 7 url. getPath (); // get the file path 8 url. getFile (); // file name, including file path + parameter 9 url. getRef (); // relative path, that is, the anchor, that is, the content 10 url after. getQuery (); // query a string, that is, a parameter

 

2. You can use the openStream () method of the URL object to obtain the input stream of a specified resource and use the stream to read or access resources on the webpage.
1 // use URL to read web content 2 // create a URL instance 3 URL = new url ("http://www.baidu.com"); 4 InputStream is = URL. openStream (); // use the openStream method to obtain the resource's byte input stream 5 InputStreamReader isr = newInputStreamReader (is, "UTF-8"); // converts a byte input stream to a character input stream, if no encoding is specified, garbled characters may occur in Chinese. 6 BufferedReader br = newBufferedReader (isr); // Add a buffer to the character input stream to improve reading efficiency. 7 String data = br. readLine (); // read data 8 while (data! = Null) {9 System. out. println (data); // output data 10 data = br. readerLine (); 11} 12 br. close (); 13 isr. colose (); 14 is. close ();

 

Iv. TCP programming 1. The TCP protocol is connection-oriented, reliable, ordered, and sends data in byte streams. connections are established through three-way handshakes to form a channel for data transmission, massive Data Transmission in the connection, efficiency will be slightly lower 2. ServerSocket class on the Socket-type server side of the client that implements network communication based on the TCP protocol in Java 3. Socket communication steps ① create ServerSocket and Socket ② open the input connected to the Socket /output stream ③ perform read/write operations on the Socket according to the protocol ④ close the input/output stream, close Socket 4. server side: ① create a ServerSocket object and bind the listening port ② listen to the client request through the accept () method ③ After the connection is established, read the request information sent by the client through the input stream ④ send the Home Information to the client through the output stream ⑤ close related resources
1/** 2 * TCP-based Socket communication for user login, Server 3 */4 // 1. Create a server Socket, that is, ServerSocket, and 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, wait for the client to connect to 7 Socket socket = serverSocket. accept (); 8 // 3. Obtain the input stream and read the client information. 9. InputStream is = socket. getInputStream (); 10 InputStreamReader isr = newInputStreamReader (is); 11 BufferedReader br = newBufferedReader (isr); 12 St Ring info = null; 13 while (info = br. readLine ())! = Null) {14 System. out. println ("I Am a server, the client said:" + info); 15} 16 socket. shutdownInput (); // close the input stream 17 // 4. Obtain the output stream and respond to the client's request 18 OutputStream OS = socket. getOutputStream (); 19 PrintWriter pw = new PrintWriter (OS); 20 pw. write ("Welcome! "); 21 pw. flush (); 22 23 24 // 5. Close resource 25 pw. close (); 26 OS. close (); 27 br. close (); 28 isr. close (); 29 is. close (); 30 socket. close (); 31 serverSocket. close ();

 

5. Client: ① create a Socket object, specify the address of the server to be connected and the port number ② after the connection is established, sending request information through the output stream to the server ③ obtaining server response information through the input stream ④ disabling response resources
1 // client 2 // 1. Create a client Socket, specify the server address and port 3 Socket = newSocket ("localhost", 10086); 4 // 2. Obtain the output stream, send information to the server 5 OutputStream OS = socket. getOutputStream (); // byte output stream 6 PrintWriter pw = newPrintWriter (OS); // wrap the output stream into a print Stream 7 pw. write ("User name: admin, password: 123"); 8 pw. flush (); 9 socket. shutdownOutput (); 10 // 3. Obtain the input stream and read the server response information. 11. InputStream is = socket. getInputStream (); 12 BufferedReader br = new BufferedReader (new Input StreamReader (is); 13 String info = null; 14 while (info = br. readLine ())! Null) {15 System. out. println ("I Am a client, the server said:" + info); 16} 17 18 // 4. Disable resources 19 br. close (); 20 is. close (); 21 pw. close (); 22 OS. close (); 23 socket. close ();

 

6. implement multi-thread communication between servers and multiple clients. ① create a ServerSocket on the server and call accept () cyclically () wait for the client to connect ② the client creates a socket and requests to connect to the server ③ the server side accepts the bitter read segment request, create a socket and establish a leased line connection with the customer. ④ establish two sockets connected to the customer and talk to each other in a separate thread. ⑤ the server continues to wait for the new connection.
1 // server thread processing 2 // socket 3 Socket socket related to this thread = null; 4 // 5 public serverThread (Socket socket) {6 this. socket = socket; 7} 8 9 publicvoid run () {10 // server processing code 11} 12 13 // ============================== ======================= 14 // server code 15 ServerSocket serverSocket = newServerSocket (10086 ); 16 Socket socket = null; 17 int count = 0; // record the number of clients 18 while (true) {19 socket = serverScoket. accept (); 20 ServerThread serverThread = newServerThread (socket); 21 serverThread. start (); 22 count ++; 23 System. out. println ("number of client connections:" + count); 24}

 

5. UDP programming UDP protocol (User Datagram Protocol) is connectionless, unreliable, and unordered. When data transmission is fast, first, the data to be transmitted is defined as a data packet. The data size is limited to 64 KB. In the data packet, specify the Socket (host address and port number) to which the data is requested ), then, the data packet is sent out to the mongorampacket class, which indicates the packet ingress ramsocket class: Class 1 for end-to-end communication. Step 1: Create an ingress ramsocket on the server, specify port number ② create mongorampacket ③ accept the data information sent by the client ④ read the data
1 // server side for UDP-based user login 2 // 1. Create a server-side ingress ramsocket and specify Port 3 ingress ramsocket socket = new ingress ramsocket (10010 ); 4 // 2. Create a datagram to accept the data sent by the client. 5 bytes [] data = newbyte [1024]; // 6 bytes rampacket packet = new1_rampacket (data, data. length); 7 // 3. Accept the data sent by the Client 8 socket. receive (packet); // This method will consistently block 9 // 4, read data 10 String info = newString (data, o, data. length); 11 System. out. println ("I Am a server, the client tells me" + info); 12 13 14 // ==== ========================================================== =============15 // return data to the client 16 // 1. Define the client address, port number, and data 17 InetAddress address = packet. getAddress (); 18 int port = packet. getPort (); 19 byte [] data2 = "Welcome! ". GeyBytes (); 20 // 2. Create a datagram that contains the response data information 21. DatagramPacket packet2 = new DatagramPacket (data2, data2.length, address, port ); 22 // 3. Response client 23 socket. send (packet2); 24 // 4. Disable resource 25 socket. close ();

 

2. Client implementation step ① define sending information ② create ingress rampacket, including the information to be sent ③ create ingress ramsocket ④ send data
1 // client 2 // 1. Define the server address, port number, and data 3 InetAddress address = InetAddress. getByName ("localhost"); 4 int port = 10010; 5 byte [] data = "username: admin; Password: 123 ". getBytes (); 6 // 2. Create a datagram that contains the sent data information. 7. DatagramPacket packet = newDatagramPacket (data, data, length, address, port ); 8 // 3. Create the initramsocket object 9 initramsocket socket = newinitramsocket (); 10 // 4. send data to the server 11 socket. send (packet ); 12 13 14 // accept the server response data 15 // ========================== ============ 16 // 1. Create a datagram, used to receive server response data 17 bytes [] data2 = new byte [1024]; 18 bytes rampacket packet2 = new bytes rampacket (data2, data2.length ); 19 // 2. Accept the Server Response Data 20 socket. receive (packet2); 21 String raply = new String (data2, 0, packet2.getLenth (); 22 System. out. println ("I Am a client, the server said:" + reply); 23 // 4. Disable resource 24 socket. close ();

 

Vi. Attention: 1. Priority of multithreading: based on actual experience, appropriately reduce the priority. Whether to disable the output stream and input stream may cause low program running efficiency. 2. Whether to disable the output stream and input stream: for the same socket, if the output stream is closed, the socket associated with the output stream is also closed, so the stream is generally not closed, directly close the socket. 3. use TCP communication to transmit objects. serialization in IO. 4. Use socket programming to transfer files and IO streams.

Related Article

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.