Network Programming-Socket programming based on TCP protocol, Socket programming based on UDP protocol, and socketudp

Source: Internet
Author: User

Network Programming-Socket programming based on TCP protocol, Socket programming based on UDP protocol, and socketudp

Socket programming

Currently, the popular network programming model is the client/server communication mode.

The customer process sends a request to the server process requesting a certain service. The server process responds to the request ., Generally, a server process serves multiple client processes at the same time. In the preceding figure, server process B1 provides services for the customer process A1, A2, and B2 at the same time.

 

Socket Overview

① The so-called Socket is also called a "Socket", which is used to describe the IP address and port. It is a communication chain handle. Applications usually send requests to or respond to network requests through sockets.

② Socket is the two-way communication endpoint between two programs running on the network.

③ Network communication refers to inter-Socket communication.

④ Both ends of the communication have sockets, and data is transmitted through IO between the two sockets.

 

Network Communication using Socket

① The server program binds a socket to a specific port and waits for and listens to the client's connection request through the socket.

② The customer program sends a connection request based on the host and port number of the server program.

③ If everything is normal, the server accepts the connection request. And obtain a new socket bound to different port addresses.

④ The customer communicates with the server through the Read and Write sockets.

 

Socket programming based on TCP protocol

① Steps to create a TCP Server:

A) create a ServerSocket object

B) Call the accept () method to accept client requests

C) obtain the I/O stream from the Socket

D) read and write the I/O Stream to complete interaction with the client.

E) disable the I/O Stream and Socket

② Procedure for creating a TCP client:

A) create a Socket object

B) obtain the I/O stream from the Socket

C) read and write the I/O Stream to complete interaction with the server.

D) disable the I/O Stream and Socket.

Note: when data is transmitted between the client and the server, the input stream of the client corresponds to the output stream of the server, and the output stream of the client corresponds to the input stream of the server.

 

Example: Create a client to communicate with the server

Package name: com. iotek. tcpsocket

Server:

1 // 1. create a ServerSocket object 2 ServerSocket serverSocket = new ServerSocket (8888); 3 // 2. call the accept () method to accept the client request 4 Socket socket = serverSocket. accept (); 5 System. out. println (socket. getInetAddress (). getHostAddress () + "connection successful"); 6 // 3. obtain the input/output stream of the socket object. 7 BufferedReader br = new BufferedReader (new InputStreamReader (8 socket. getInputStream (); 9 10 PrintWriter pw = new PrintWriter (socket. getOutputStream (), True); 11 String line = null; 12 // read the data transmitted from the client 13 while (line = br. readLine ())! = Null) {14 if (line. equals ("over") {15 break; 16} 17 System. out. println (line); 18 pw. println (line. toUpperCase (); 19} 20 21 pw. close (); 22 br. close (); 23 socket. close (); 24 System. out. println (socket. getInetAddress (). getHostAddress () + "Disconnect ");

 

Client:

1 Socket socket = new Socket ("127.0.0.1", 8888); 2 BufferedReader br = new BufferedReader (new InputStreamReader (System. in); 3 4 PrintWriter pw = new PrintWriter (socket. getOutputStream (), true); 5 BufferedReader reader = new BufferedReader (new InputStreamReader (6 socket. getInputStream (); 7 while (true) {8 String line = br. readLine (); // obtain the string 9 pw entered by the keyboard. println (line); 10 if (line. equals ("over") {11 break; 12} 13 System. out. println (reader. readLine (); // obtain the uppercase string uploaded by the server 14} 15 reader. close (); 16 br. close (); 17 pw. close (); 18 socket. close ();

To more intuitively see the communication process, copy the two java programs to the root directory of the E disk and run them in the form of a command line.

Open cmd and compile java.

① Enter the edisk. E:

② Compile all java files. Javac-d. *. java

③ Open the server. Java com. iotek. tcpsocket. TCPServer

④ Open a cmd command line to open the client java com. iotek. tcpsocket. TCPClient

Connection successful

After the client inputs hello and press enter, the test is successful.

Input over to disconnect

 

UDP-based Socket programming

① Create a sender

A) create an initramsocket object. This endpoint is created and the system will randomly allocate a port. If you do not want to configure it randomly, You can manually specify it.

B) To encapsulate data in a packet package, you must specify the destination address and port.

C) send the package through the send method of the socket service.

D) disable the socket.

② Create an acceptor

A) create an initramsocket object. Listen to a port.

B) store data into data packets through the socket receive method.

C) Get the specified information in the package through the methods of data packet dp, such as getData (), getAddress (), and getPort.

D) disable the socket.

 

Example: Create an example of sending and receiving

Sender: UDPDemo1

1) DatagramSocket socket = new DatagramSocket (); 2 String str = "I love you"; 3 // encapsulate data into a datagram package. 4) rampacket packet = new DatagramPacket (str. getBytes (), 5 str. length (), InetAddress. getByName ("localhost"), 6666); 6 socket. send (packet); // send 7 8 byte [] buff = new byte [100]; 9 bytes rampacket packet2 = new bytes rampacket (buff, 100); 10 socket. receive (packet2); 11 System. out. println (new String (buff, 0, packet2.getLength (); 12 socket. close ();

 

Receiver: UDPDemo2

1 // receive data first 2 bytes ramsocket socket = new bytes ramsocket (6666); 3 byte [] buff = new byte [100]; 4 bytes rampacket packet = new bytes rampacket (buff, 100 ); 5 socket. receive (packet); // receives 6 System data packets. out. println (new String (buff, 0, packet. getLength (); 7 8 // send data 9 String str = "me too"; 10 bytes rampacket packet2 = new bytes rampacket (str. getBytes (), 11 str. length (), packet. getAddress (), packet. getPort (); 12 socket. send (packet2); 13 socket. close ();

 

Copy the two java programs to the root directory of the E drive and run them in the form of a command line.

Open cmd and compile java. steps:

① Enter the edisk. E:

② Compile a file starting with UDP. Javac-d. UDP *. java

③ Run the acceptor first. Java com. iotek. tcpsocket. UDPDemo2

④ Re-open a command line and run the sender. Java com. iotek. tcpsocket. UDPDemo1

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.