The original address: Java socket programming----communication is so refined
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 Network Basics points:
- The following three conditions are required for communication between two computers
IP address, protocol, port number:
- IP Address: Locate the network location of the machine where the application resides. (e.g. home address: xx Street xx District, Chaoyang District, Beijing)
- Port number: The specified application that uniquely identifies the machine. House number
- Protocol: The form of data transmission. (TCP, UDP, etc.)
-
IP Address
To enable communication between different computers in the network, each computer must have a unique identity---IP address.
-
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.
-
Socket sockets:
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 are available at both ends of the communication.
Network communication is actually the communication between sockets.
Data is transmitted via IO between two sockets.
- 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 directly read or write data 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.
InetAddress
The InetAddress class represents a network destination address, including host name and IP address information.
The class does not have any constructor methods.
//Get the host name and IP address of the machineInetAddress address = inetaddress.Getlocalhost(); String hostName = address.GetHostName();//Get computer name (native hostname is computer name)String hostaddress = address.gethostaddress();//Get IP addressSystem. out.println("HostName:"+ HostName +"&hostaddress:"+ hostaddress);//Get the host name and IP address of the remote machineInetAddress addr = inetaddress.Getbyname("Www.baidu.com");//Do not add a protocol here such as: Http://www.baidu.comString domainName = addr.GetHostName();//Get host nameString ipname = addr.gethostaddress();//Get an IP addressSystem. out.println("DomainName:"+ DomainName +"&ipname:"+ Ipname);
Using URL network resources
The OpenStream () method of the URL object allows the input stream of the specified resource to be read or accessed through the stream to resources on the Web page.
//使用URL读取网页内容new URL("http://www.baidu.com");InputStream is = url.openStream();//通过openStream方法获取资源的字节输入流new InputStreamReader(is,"UTF-8");//将字节输入流转换为字符输入流,如果不指定编码,中文可能会出现乱码new BufferedReader(isr);//为字符输入流添加缓冲,提高读取效率String data = br.readLine();//读取数据while(data!=null){ System.out.println(data);//输出数据 data = br.readLine();}br.close();is.close();
TCP programming Model
TCP protocol is a connection-oriented, reliable, orderly, byte-stream transmission of data, through the three-time handshake to establish a connection, the channel to form the transmission of data, in the connection of a large number of data transmission, the efficiency will be slightly lower.
Classes in Java that implement network traffic based on the TCP protocol:
- The socket class for the client.
- The ServerSocket class on the server side.
Steps for Socket communication:
- Create ServerSocket and sockets.
- Open the input and output streams connected to the socket.
- Read and write the socket according to the TCP protocol.
- Close the input and output stream and close the socket.
Server-side:
- Creates a ServerSocket object that binds the listening port.
- Listens for client requests through the accept () method.
- After the connection is established, read the request information sent by the client through the input stream.
- Sends a response message through the output flow to the client.
- Close related resources.
/*** Socket communication based on TCP protocol, to realize user login, service side *////1, create a server-side socket, that is, ServerSocket, specify the bound port, and listen to this portServerSocket ServerSocket =NewServerSocket (10086);a port for//1024-65535///2, call the Accept () method to start listening, waiting for the client to connectSocket socket = ServerSocket.Accept();///3, get input stream, and read client informationInputStream is = socket.getInputStream(); InputStreamReader ISR =NewInputStreamReader (IS); BufferedReader br =NewBufferedReader (ISR); String info =NULL; while(info = br.)ReadLine()) !=NULL) {System. out.println("I am the server," said the client, "+ info);} Socket.Shutdowninput();//Close input stream///4, get output stream, respond to client's requestOutputStream OS = socket.Getoutputstream(); PrintWriter PW =NewPrintWriter (OS);p W.Write("Welcome you!" ");p W.Flush();///5, Close resourcespw.Close(); OS.Close(); Br.Close(); ISR.Close();Close(); socket.Close();
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, send the request information through the output to the server side.
- Get information about the server response via the input stream
- Close related resources.
///1, create client socket, specify server address and portSocket socket =NewSocket ("localhost",10086);///2, get output stream, send information to server sideOutputStream OS = socket.Getoutputstream();//Byte output streamPrintWriter PW =NewPrintWriter (OS);//Package The output stream as a print streampw.Write("user name: admin; Password: 123");p W.Flush(); socket.Shutdownoutput();///3, gets the input stream and reads the server-side response informationInputStream is = socket.getInputStream(); BufferedReader br =NewBufferedReader (NewInputStreamReader (IS)); String info =NULL; while(INFO=BR.ReadLine())!=NULL) {System. out.println("I'm the client," said the server .+info);}///4, Close resourcesBr.Close();Close();p W.Close(); OS.Close(); socket.Close();
Multithreading enables the communication between the server and the client.
The server-side loop calls accept () to wait for the client to connect. After the server receives the data, it is handed over to one thread for asynchronous processing, and then waits for the client to connect again.
StaticExecutorservice executor = executors.Newfixedthreadpool(Ten); Public Static void Main(string[] args)throwsException {/*** Socket communication based on TCP protocol, to realize user login, service side */ ///1, create a server-side socket, that is, ServerSocket, specify the bound port, and listen to this portServerSocket ServerSocket =NewServerSocket (10086);a port for//1024-65535 ///2, call the Accept () method to start listening, waiting for the client to connect while(true) {executor.Execute(New Servertask(ServerSocket.Accept())); }}Static classServertaskImplementsRunnable {socket socket; Public Servertask(Socket socket) { This.Socket= socket; }@Override Public void Run() {Try{///3, get input stream, and read client informationInputStream is = socket.getInputStream(); InputStreamReader ISR =NewInputStreamReader (IS); BufferedReader br =NewBufferedReader (ISR); String info =NULL; while(info = br.)ReadLine()) !=NULL) {System. out.println("I am the server," said the client, "+ info); } socket.Shutdowninput();//Close input stream ///4, get output stream, respond to client's requestOutputStream OS = socket.Getoutputstream(); PrintWriter PW =NewPrintWriter (OS); pw.Write("Welcome you!" "); pw.Flush();//demo will not be put in finally closedIs.Close(); Isr.Close(); Os.Close(); pw.Close(); }Catch(Exception e) {e.Printstacktrace(); } }}
UDP programming Model
The UDP protocol (User Datagram Protocol) is non-connected, unreliable, unordered, and fast.
In the data transmission, the data to be transmitted is defined as a datagram (Datagram) with a size limit of 64k, in which the data is requested to reach the socket (host address and port number), and then the datagram is sent out.
Datagrampacket class: Represents a Datagram package
Datagramsocket class: Classes for end-to-end communication
Server-side implementation steps:
+ 创建DatagramSocket,指定端口号 + 创建DatagramPacket + 接受客户端发送的数据信息 + 读取数据
//server-side, implementation of UDP-based user login///1, create server-side datagramsocket, specify PortDatagramsocket socket =NewDatagramsocket (10010);///2, create a staged data packet to accept the data sent by the clientbyte[] data =New byte[1024x768];D Atagrampacket packet =NewDatagrampacket (Data,data.length);///3, accept the data sent by the clientSocket.Receive(packet);//This method will block consistently until the datagram is accepted///4, read dataString info =NewString (data); System. out.println("I am the server, the client told me:"+info);//Response data to client///1, define the client's address, port number, dataInetAddress address = packet.getaddress();intPort = packet.Getport();byte[] Data2 ="Welcome you!" ".getBytes();///2, create a datagram that contains the data information of the responseDatagrampacket Packet2 =NewDatagrampacket (Data2,data2.length, Address,port);//3, Response clientSocket.Send(Packet2);///4, Close resourcesSocket.Close();
Client implementation steps:
- Defines the sending message.
- Create a datagrampacket that contains the message that will be sent.
- Create a datagramsocket.
- Send data.
//Client///1, define the server's address, port number, dataInetAddress address = inetaddress.Getbyname("localhost");intPort =10010;byte[] data ="user name: admin; Password: 123".getBytes();//2, create a datagram that contains the data sentDatagrampacket packet =NewDatagrampacket (data, data.length, address, Port);///3, create Datagramsocket objectDatagramsocket socket =NewDatagramsocket ();///4. Send data to the serverSocket.Send(packet);//Accept server-side response data//======================================///1, create datagrams to accept server-side response databyte[] Data2 =New byte[1024x768];D Atagrampacket Packet2 =NewDatagrampacket (Data2, data2.length);///2, accept the server response dataSocket.Receive(Packet2); String raply =NewString (Data2,0, Packet2.GetLength()); System. out.println("I'm the client," said the server .+ raply);///4, Close resourcesSocket.Close();
Note the problem:
1, multi-threaded priority issues:
Based on practical experience, proper reduction of priority, no side may have low efficiency of program operation
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
Java Socket Programming Basics