Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

UDP-TCP

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

one。 Basic concepts related to network

1. Network communication protocol: it is a common network language, which provides communication support for Internet guides connecting different operating systems and different hardware architectures. There are many specific types of communication protocols, including UDP protocol and T CP protocol.

2.UDP protocol: is the abbreviation of User Datagram Protocol, the Chinese name is the user Datagram protocol. Is a connectionless protocol. High transmission efficiency; data is insecure and easy to lose

Features:

1: for connectionless

2: high efficiency

3: not safe

3.TCP/IP Protocol: abbreviation of Transmission Control Protocol/Internet Protocol, translated into Chinese as Transmission Control Protocol / Internet Interconnection Protocol

Features:

1: connection-oriented; (client and server need to establish a connection in advance before they can communicate, 3-way handshake)

2: low efficiency

3: data security

4. Network protocol data transmission process: from bottom to top: link layer-network layer-transport layer-application layer

Link layer: software driver and hardware interface

Network layer: data grouping and processing, IP address, port number

Transport layer: the core of the network communication protocol, where data is transmitted over the network.

Application layer: application-level software, mainly for data analysis

5.IP address: is the unique identity of the participant in the network. Contains IPV4/IPV6.IPV4 using 4 bytes to represent IP addresses; each byte can only range from 0 to 255.

6. Port number: it is used to identify different processes in a computer; it uses 2 bytes to represent a port number in the range of 0-65535 (2 ^ 16 = 65536), in which 0-1024 port number has been occupied by the computer's core services. Programmers are advised to use 1024.

The port number of.

II. InetAddress class (java.net)

Introduction: InetAddress is a class written by java to describe the ip address of a computer

Constructor: the InetAddress constructor cannot be used directly, so you must get the object through the static method:

Inheritance relationship: java.lang.Object--java.net.InetAddress

Definition: public class InetAddress extends Object implements Serializable

Static method:

Public static InetAddress getByName (String host) {}: determine the IP address of the host given the hostname

Public static InetAddress getLocalHost () throws UnknownHostException {}: returns the local host

Common methods:

Public String getHostAddress () {}: returns the IP address string (in text form)

Public String getHostName () {}: get the hostname of this IP address

Code demonstration:

Import java.net.InetAddress;import java.net.UnknownHostException;public class NetDemo {public static void main (String [] args) {/ / get the local host and return the InetAddress object InetAddress host = null;try {host = InetAddress.getLocalHost ();} catch (UnknownHostException e) {e.printStackTrace ();} System.out.println (host); / / get the local host name String name = host.getHostName (); / / get the local ipString ip = host.getHostAddress (); System.out.println ("computer name:" + name+ ") Ip is: "+ ip); / / get the IPtry {host = InetAddress.getByName (" LWL ") of someone else's computer through their computer name;} catch (UnknownHostException e) {e.printStackTrace ();} String ip1 = host.getHostAddress (); System.out.println (ip1);}

II. Common UDP classes

1.DatagramPacket class (java.net)

Inheritance relationship: java.lang.Object--java.net.DatagramPacket

Definition: public final class DatagramPacket extends Object

Construction method:

DatagramPacket (byte [] buf, int length, InetAddress address, int port): constructs a Datagram packet, which is used to send packets of length length to the specified port number on the specified host.

Buf: array to hold the data to be sent

Length: length of data to be sent

Address: the recipient's ip address object

Port: Port number of the recipient

This object is used on the sender.

DatagramPacket (byte [] buf, int length): construct a DatagramPacket to receive packets of length length.

Buf: the data sent by the sender will be saved to the buf array

Length: represents an array of DatagramPacket objects, and how many positions can be used

This object is used on the receiving end.

Commonly used main method:

Public byte [] getData () {}: Returns the data buffer. The data received or the data to be sent starts from the offset in the buffer, and runs for length

Long.

Public int getLength () {}: Returns the length of the data to be sent or the length of the data received.

2.DatagramSocket class (java.net)

Inheritance relationship: java.lang.Object--java.net.DatagramSocket

Definition: public class DatagramSocket extends Object implements Closeable

Construction method:

DatagramSocket () throws SocketException: construct a Datagram socket and bind it to any available port on the local host.

(this object is generally used on the sending side, through which the Datagram packet object can be sent.)

DatagramSocket (int port): creates a Datagram socket and binds it to the specified port on the local host. (it is generally used on the receiving end to listen to the specified port number and can receive Datagram packets sent by others to the port)

Common methods:

Public void send (DatagramPacket p) throws IOException {}: sends a Datagram packet from this socket

Public void receive (DatagramPacket p) throws IOException {}: receives Datagram packets from this socket.

This method has the effect of thread blocking, so the method must be called at the receiver before the sender can send the Datagram packet, otherwise the Datagram packet will be lost.

3.UDP communication case

/ / UDP communication implementation: Receiverimport java.net.DatagramPacket;import java.net.DatagramSocket;public class UDPReceiver {public static void main (String [] args) throws Exception {/ / Datagram packet object byte [] b = new byte [1024]; DatagramPacket dp = new DatagramPacket (b, b.length); / / create receiver object DatagramSocket ds = new DatagramSocket (8891); / / receiver uses its own Datagram packet object to receive the transmitted data ds.receive (dp) / / get array and effective length byte [] bs = dp.getData (); int I = dp.getLength (); / / turn string String s = new String (bs, 0, I); System.out.println ("sender says:" + s); ds.close ();}} / / UDP communication implementation: senderimport java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.util.Scanner Public class UDPSender {public static void main (String [] args) throws Exception {/ / prompt the sender to enter the send message Scanner sc = new Scanner (System.in); System.out.println ("Please enter the message to be sent::"); String message = sc.next (); / / convert the entered message into a byte array byte [] b = message.getBytes () / / encapsulate the original data into a DatagramPacket object DatagramPacket dp = new DatagramPacket (b, b.new DatagramSocket. GetLocalHost (), 8891); / / create a sender object DatagramSocket ds = LocalHost (); / / send the encapsulated DatagramPacket object to ds.send (dp) using the sender object; / / close the stream ds.close ();}}

III. Common TCP classes

1.Socket

Introduction: a class used to represent the client. In the TCP protocol, the interaction between the client and the server is completed through the IO stream, and all IO stream objects are provided by the client!

Inheritance relationship: java.lang.Object--java.net.Socket

Definition: public class Socket extends Object implements Closeable

Construction method:

Socket (String host, int port) throws UnknownHostException,IOException: creates a stream socket and connects it to the specified port number on the specified host. If the client object can be created successfully, the 3-way handshake has been successful!

2.ServerSocket

Introduction: a class used to represent the server side

Inheritance relationship: java.lang.Object--java.net.ServerSocket

Definition: public class ServerSocket extends Object implements Closeable

Construction method:

ServerSocket (int port) throws IOException: creates a server socket bound to a specific port. In actual development, there is a server object before the client can access it, so the person who created the server object can specify a port number.

Common methods:

Public Socket accept () throws IOException {}: listen for and receive a connection to this socket. This method has the effect of thread blocking, and if no client accesses the server, the current thread of the server will remain blocked.

3.TCP communication case

/ / client import java.io.IOException;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;import java.util.Scanner;public class TCPClientDemo {public static void main (String [] args) throws UnknownHostException,IOException {/ / create client object Socket s = new Socket ("127.0.0.1", 9999); / / get the output stream in the network for client object OutputStream out = s.getOutputStream () / / write data to the network Scanner sc = new Scanner (System.in); System.out.println ("Please enter the message to be sent:"); String str = sc.next (); out.write (str.getBytes ());}}

/ / server-side import java.io.IOException;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;public class TCPReceiverDemo {public static void main (String [] args) throws IOException {/ / create server-side object ServerSocket ss = new ServerSocket (9999); / / Let server-side object wait for client connection acceptSocket s = ss.accept (); / / oriented Socket object, get input stream object InputStream in = s.getInputStream () / / read byte [] b = new byte [1024]; int I = in.read (b); / / convert to string output String str = new String (b, 0, I); System.out.println ("message from client:" + str);}}

4. File upload case multithreaded version

/ * File upload server-side multithreading * / import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class FileloadServer {public static void main (String [] args) throws Exception {/ / create server-side object ServerSocket ss = new ServerSocket (8870); / / throws IOException// listener port to form blocking state while (true) {final Socket s = ss.accept () / / throws IOExceptionnew Thread () {@ Overridepublic void run () {try {/ / I am a program in the server. I want to create a local write stream network input stream-local output stream-local file InputStream in = s.getInputStream (); FileOutputStream fout = new FileOutputStream (System.currentTimeMillis () + ".jpg"); / / I am a program in the server, and I want to read the message int I =-1 sent from the client Byte [] b = new byte [1024]; while ((I = in.read (b))! =-1) {fout.write (b, 0, I); / / write to local disk} / / notify client that upload succeeded OutputStream out = s.getOutputStream (); out.write ("upload succeeded" .getBytes ());} catch (Exception e) {e.printStackTrace ();} .start () } / * upload file client * / import java.io.FileInputStream;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;public class FileUploadClient {public static void main (String [] args) throws Exception {/ / create local file input stream I am the program: local file-local file input stream-network output stream FileInputStream fin = new FileInputStream ("E:\\ JAVAPractice\\ net\\ 1.jpg") / / throws FileNotFoundException// create client object Socket s = new Socket ("127.0.0.1", 8870); / / throws UnknownHostException,IOException// get output stream for client OutputStream out = s.getOutputStream (); / / throws IOException// loop write network int I =-1 X byte [] b = new byte [1024]; while ((I = fin.read (b))! =-1) {out.write (b, 0, I) } / / notify the server that the circular output is complete-solve the deadlock problem s.shutdownOutput (); / / throws IOException// notify the client InputStream in = s.getInputStream () if the file is uploaded; / / throws IOExceptioni = in.read (b); String message = new String (b, 0, I); / / Throws IndexOutOfBoundsExceptionSystem.out.println ("message from server:" + message);}}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report