Current location - Quotes Website - Collection of slogans - Do network communication JAVA development, mainly learning content?
Do network communication JAVA development, mainly learning content?
1.IP address and port number

If computers in the network need to communicate with each other, each computer must be assigned an identification number, and the computers receiving data and sending data must be identified by the identification number. The "logo" in TCP/IP protocol is the IP address.

A computer can run multiple network programs at the same time. Using an IP address can send data to a computer, but there is no guarantee that the data will be submitted to which network program. Therefore, the header of each transmitted network packet has a "port" part, which is an integer to indicate to which application the data frame is handed over for processing. At the same time, you must specify the port number for the network program so that different applications can receive data on different ports.

Multiple programs using the same port cannot exist on the same computer. The range of port numbers is 0-65535, where the port number between 0- 1023 is used for well-known network services and applications, and the port number above 1024 is used for ordinary applications, which can avoid the crosstalk of network programs represented by port numbers.

2.TCP and UDP

TCP is the transmission control protocol and UDP is the user datagram protocol. TCP is a connection-oriented communication protocol, which provides reliable and error-free data transmission between two computers. When an application uses TCP to communicate, a virtual connection will be established between the data source and the target. Once the connection is established, data can be exchanged between two computers in the form of two-way byte streams.

UDP is a connectionless communication protocol, which does not guarantee the reliable transmission of data, but can realize the function of sending data to multiple targets.

3.3 Introduction. (power supply) socket

Socket is an interface and mechanism provided by the network driver layer for applications, and its function can be regarded as a port dock created for applications.

4. Overview 4. TCP network programming

The specific operation steps of TCP protocol are as follows:

(1) The server program creates the ServerSocket object and calls the accept () method to wait for the client to connect.

(2) The client program creates a Socket object to establish a dedicated line connection with the client.

(3) The server receives the connection request from the client, creates a new Socket object, and establishes a dedicated line connection with the client.

(4) The two sockets established in steps (2) and (3) can talk on the same thread.

(5) The server waits for a new connection request again.

5.ServerSocket class

The writing of TCP network server program needs to use ServerSocket class to create the server.

The main methods of ServerSocket class are as follows:

Method type description

The public ServerSocket(int port) constructor creates an instance of ServerSocket.

The public socket accept () method waits for a client connection.

The public inetaddress get inetaddress () method returns the IP address of the server.

The public boolean isClosed () method returns the closed state of the ServerSocket.

The publicovoid close () method closes the server socket.

Every time the server runs, it needs to call the accept () method to wait for the client to connect. After this method is executed, the server will enter a blocking state until the client connects again. The return type of the accept () method is Socket.

6. Socket class

The client must create socket objects to establish a connection with the server, and each socket object represents a client.

The common methods of Socket class are as follows:

Method type description

The public Socket (string host, int port) constructor creates a Socket object and specifies the host name and commodity number of the server to be connected.

The public input stream get input stream () method returns the input stream of the socket.

The public output stream get output stream () method returns the output stream of the socket.

The public boolean isClosed () method returns the closed state of the socket.

The public void close () method closes this socket.

Note: the information in TCP network programming is transmitted in the form of iostream.

7.TCP server program

Write TCP server program, the code is as follows:

Bao com

Import java.net. *;

Import java.io. *;

Common class TcpServer{

Public static void main(String []a){

ServerSocket server = null

Socket socket = null

BufferedReader in = null

PrintWriter out = null

Try {

//The server listens on port 9000.

server = new server socket(9000);

//Receive client connection

socket = server . accept();

//Get the information input by the client.

in = new buffered reader(new InputStreamReader(socket . getinputstream()));

//Output information to the client, if true, the buffer will be automatically refreshed.

out = new PrintWriter(socket . get output stream(),true);

Out.println ("establish a connection with the server");

string info = in . readline();

System.out.println ("input from client:"+info ");

}catch (exception e){

e . printstacktrace();

}

Finally {

Try {

in . close();

out . close();

socket . close();

server . close();

}catch (exception e){

e . printstacktrace();

}

}

}

}

In order to verify whether the server-side program can work normally, the program also needs to provide the client-side program to communicate with the server. Telnet program in Windows system is the TCP client that comes with the system. Telnet can be used to test communication with the server. When running telnet, specify the IP address and port number of the connecting server. Once the connection is established, the telnet program window can send the input to the server and display the data received from the server. The test steps are as follows:

(1) Run the server program.

(2) Run telnet127.0.0.19000 in the DOS window. Because the server-side program and the client-side program are on the same machine, 127.0.0. 1 can be used to represent this machine.

Note: You can only accept one connection at a time by calling the accept () method. To accept multiple connections, the method should be put in a loop statement, and the data input and output of each connection should also be put in a loop statement, so as to realize the continuous exchange between the server and the client.

Class service implementation Runnable{

Socket socket = null

BufferedReader in = null

PrintWriter out = null

Public Service (Socket Socket)

this.socket = socket

}

Public invalid operation () {

//Get the information input by the client.

in = new buffered reader(new InputStreamReader(socket . getinputstream()));

//Output information to the client, if true, the buffer will be automatically refreshed.

out = new PrintWriter(socket . get output stream(),true);

//Read the client data circularly and write the data to the client.

while(true){

Out.println ("establish a connection with the server");

System.out.println ("the client says:"+in.readline ());

}

}

Catch (exception e)

e . printstacktrace();

}

Finally {

Try {

in . close();

out . close();

socket . close();

server . close();

}catch (exception e){

e . printstacktrace();

}

}

}

}

Common class TcpServer{

ServerSocket server = null

Socket socket = null

Try {

//The server listens on port 9000.

server = new server socket(9000);

//Receive multiple client connections

while(true){

socket = server . accept();

New thread (new service (socket)). start();

}catch (exception e){

e . printstacktrace();

}

}

}

8.TCP client program

Bao com

Import java.net. *;

Import java.io. *;

Common class TcpClient{

Public static void main(String []a){

ServerSocket server = null

Socket socket = null

BufferedReader in = null

BufferedReader input = null

PrintWriter out = null

Try {

Socket = new socket ("127.0.0. 1", 9000);

while(true){

Input=new BufferedReader (new InputStreamReader(system. in));));

in = new buffered reader(new InputStreamReader(socket . getinputstream()));

}

//Output information to the server. If true, the buffer will be automatically refreshed.

out = new PrintWriter(socket . get output stream(),true);

Out.println ("the client says:"+input.readline);

string info = in . readline();

System.out.println ("the server says:"+info);

}catch (exception e){

e . printstacktrace();

}

}

}

9.UDP network programming

(1)DatagramSocket class is mainly used to send and receive information.

Main methods of DatagramSocket class:

Method type description

The public DatagramSocket () constructor constructs a DatagramSocket object without specifying a listening port.

The public DatagramSocket(int port) constructor constructs a DatagramSocket object to specify the listening port.

The public void send(DatagramPacket p) method sends datagrams.

The public void receive (datagram packet p) method receives datagrams.

(2)DatagramPacket class

The DatagramPacket class is used to wrap a piece of information to be sent or received. DatagramPacket objects need to be constructed to send and receive data.

The main methods of the DatagramPacket class:

Method type description

The public DatagramPacket (byte [] buf, in length) constructor specifies the memory space and size when constructing the datagram packet object.

Common datagram package (byte [] buf, length, inetaddress address, int port) is the same as above.

The public byte[] getData () method returns the received data.

The public int getLength () method returns the length of data sent or received.

The public InetAddress getAddress () method returns the address of the machine.

(3) In the classroom

The InetAddress class is used to represent the computer address, and the main methods are as follows:

Method type description

The public static inet address get by name (stringhost) method gets the inetaddress object by host name or IP address.

The public String getHostName () method gets the host name corresponding to the IP address.

The public string getHostAddress () method returns an IP address string.

10.UDP programming

Writing UDP network program needs to write sending program and receiving program separately.

(1) sender

Bao com

Import java.net. *;

Public class UdpSend{

Public static void main(String [] a){

DatagramSocket ds = null

DatagramPacket dp = null

Byte[]buf = new byte [1024];

Try {

//DatagramSocket class is used to complete the sending of messages.

ds = new datagram socket();

String info = " hello world

DP = new datagram packet(info . getbytes(),info.length,inet address . get byname(" localhost "),3000);

//Send data packets

ds . send(DP);

}catch (exception e){

e . printstacktrace();

}

finally

{

ds . close(); //After the message is sent, close the object.

}

}

}

(2) Receiving program

Bao com

Import java.net. *;

Public class UdpRecv{

Public static void main(String [] a){

DatagramSocket ds = null

DatagramPacket dp = null

Byte[]buf = new byte [1024];

Try {

//DatagramSocket class is used to complete the sending of messages.

ds = new datagram socket();

Dp = new DatagramPacket(buf,1024);

//Receive the data sent by the sender

dsreceive(DP);

String str=new String(dp.getData(),0,DP . getlength());

str = str+" from "+DP . get address . gethostaddress();

system . out . println(str);

}catch (exception e){

e . printstacktrace();

}

finally

{

ds . close(); //After the message is sent, close the object.

}

}

}