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 ProgrammingBasic 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/15883791. The following three conditions are required for communication between two computers:IP Address,agreements,Port number2. 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 stacktcp:transmission Control Protocol Transmission Protocolip:internet Protocol Internet Protocol3. TCP/IP five layer modelApplication layer: HTTP, FTP, SMTP, Telnet, etc.Transport Layer: TCP/IPNetwork layer:Data Link layer:Physical layer: Network cable, twisted pair, network card, etc.4. IP addressto enable communication between different computers in the network, each computer must have a unique identity---IP address. 32-bit binary5. Portdifferentiate 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:23The 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 UDP6. 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 communicationnetwork communication is actually the communication between socketsdata is transmitted via IO between two sockets 7. Network support in Javafor 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 addressesURL: A Uniform Resource locator that allows you to read or write data directly on the network through a URLSockets: Network communication using the TCP protocol socket-related classesDatagram: Using the UDP protocol, the data is stored in the user datagram and communicated over the network. Second, inetaddressThe 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 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 ();
four, 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, 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 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}
five, 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 ();
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 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
From for notes (Wiz)
Java Socket Programming----communication is so refined