In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you the "sample analysis of Scoket programming based on Java", which is easy to understand and clear, hoping to help you solve your doubts. Let the editor lead you to study and study the "sample analysis of Scoket programming based on Java".
First, two main problems in network programming
One is how to accurately locate one or more hosts on the network, and the other is how to reliably and efficiently transmit data after finding the host.
In the TCP/IP protocol, the IP layer is mainly responsible for the location of the network host and the routing of data transmission. A host on the Internet can be uniquely determined by the IP address.
The TCP layer provides application-oriented reliable (tcp) or unreliable (UDP) data transmission mechanism, which is the main object of network programming, generally do not need to care about how the IP layer deals with data.
At present, the more popular network programming model is the client / server (Cplink S) structure. That is, both sides of the communication wait for the client to make a request and respond as a server. The customer applies to the server when the service is needed. The server generally runs as a daemon all the time, listening to the network port, and once there is a customer request, it will start a service process to respond to the customer, and at the same time continue to monitor the service port, so that the later customers can also get the service in time.
Two types of transport protocols: TCP and UDP
TCP, short for Tranfer Control Protocol, is a connection-oriented protocol that ensures reliable transmission. Through the TCP protocol transmission, the result is a sequential error-free data stream. A connection must be established between the two pairs of socket of the sender and receiver in order to communicate on the basis of the TCP protocol. When one socket (usually the server socket) is waiting to establish a connection, the other socket can request a connection. Once the two socket are connected, they can carry out two-way data transmission, and both sides can send or receive operations.
UDP is the abbreviation of User Datagram Protocol and is a connectionless protocol. Each Datagram is an independent information, including a complete source address or destination address, which is transmitted to the destination by any possible path on the network, so whether it can reach the destination, the time of arrival and the correctness of the content can not be guaranteed.
The difference between TCP and UDP
UDP:
1. Complete address information is given in each Datagram, so there is no need to establish a connection between the sender and the receiver.
2. UDP has a size limit when transmitting data, and each Datagram to be transmitted must be limited to 64KB.
3. UDP is an unreliable protocol, and the datagrams sent by the sender do not necessarily arrive at the receiver in the same order.
TCP:
1. Connection-oriented protocol, it is necessary to establish a connection before data transmission between socket, so connection time is needed in TCP.
2. TCP transmission data size limit, once the connection is established, the socket of both sides can transmit large data in a unified format.
3. TCP is a reliable protocol that ensures that the receiver correctly acquires all the data sent by the sender.
Application:
1. TCP has strong vitality in network communication, for example, remote connection (Telnet) and file transfer (FTP) require data of indefinite length to be transmitted reliably. But reliable transmission comes at a price, and the verification of the correctness of data content will inevitably take up the processing time of the computer and the bandwidth of the network, so the efficiency of TCP transmission is not as high as UDP.
2. UDP is easy to operate and requires less monitoring, so it is usually used in client/server applications in distributed systems with high reliability in local area networks. For example, the video conference system does not require the audio and video data to be absolutely correct, as long as it is consistent. In this case, it is obviously more reasonable to use UDP.
Third, java network programming based on Socket 1. What is Socket
Two programs on the network exchange data through a two-way communication connection, and one end of this two-way link is called a Socket. Socket is usually used to achieve the connection between the client and the server. Socket is a very popular programming interface of the TCP/IP protocol, and a Socket is uniquely determined by an IP address and a port number.
However, TCP/IP is not the only type of protocol supported by Socket, so there is no inevitable relationship between the two. In Java environment, Socket programming mainly refers to network programming based on TCP/IP protocol.
2. The process of Socket communication
Server Listen (listening) whether a port has a connection request, the client side sends a Connect (connection) request to the Server side, and the server sends back an Accept (accept) message to the Client side. A connection is established. Both Server and Client can communicate with each other through Send,Write and other methods.
For a fully functional Socket, it should include the following basic structure, and its working process includes the following four basic steps:
(1) create a Socket
(2) Open the input / outflow connected to the Socket
(3) read / write Socket according to certain protocols
(4) close Socket. (in practical applications, the displayed close is not used, although this is recommended in many articles, but in my program, it may not have any impact because the program itself is relatively simple and undemanding. )
3. Create Socket
Create Socket
Java provides two classes, Socket and ServerSocket, in the package java.net to represent the client and server of a two-way connection, respectively. These are two very well encapsulated classes that are easy to use. The construction method is as follows:
Socket (InetAddress address, int port)
Socket (InetAddress address, int port, boolean stream)
Socket (String host, int prot)
Socket (String host, int prot, boolean stream)
Socket (SocketImpl impl)
Socket (String host, int port, InetAddress localAddr, int localPort)
Socket (InetAddress address, int port, InetAddress localAddr, int localPort)
ServerSocket (int port)
ServerSocket (int port, int backlog)
ServerSocket (int port, int backlog, InetAddress bindAddr)
Where address, host and port are the IP address, host name and port number of the other party in the two-way connection, stream indicates whether socket is a stream socket or Datagram socket,localPort represents the port number of the local host, localAddr and bindAddr are the addresses of the local machine (the host address of ServerSocket), and impl is the parent class of socket, which can be used to create both serverSocket and Socket. Count represents the maximum number of connections that the server can support. For example: https://www.yisu.com
Socket client = new Socket ("127.0.01.", 80); ServerSocket server = new ServerSocket (80)
Note that care must be taken when selecting ports. Each port provides a specific service, and only when the correct port is given can the corresponding service be obtained. The port number of 0Secret1023 is reserved by the system, for example, the port number of http service is 80jiao telnet service, and the port number of 21Graver ftp service is 23, so when we choose a port number, it is best to choose a number greater than 1023 to prevent conflicts.
If an error occurs when creating a socket, an IOException will be generated and must be dealt with in the program. So an exception must be caught or thrown before creating a Socket or ServerSocket.
Code demonstration example: data transfer based on TCP, transfer string
Server side:
Public class SocketServer {public static void main (String [] args) {try {/ * 1, create serverScoket object * 2, call accept () method to turn on listening * 3, get file stream (output stream or input stream) * 4, perform read and write operations * 5, close stream * 6, Close serversocket. * / ServerSocket server = new ServerSocket (8888); System.out.println ("Server started!") ; / / receive messages from the client: Socket socket = server.accept (); InputStream is = socket.getInputStream (); BufferedReader br = new BufferedReader (new InputStreamReader (is)); String info = null; while ((info = br.readLine ())! = null) {System.out.println (info) } / / write information to the client OutputStream os = socket.getOutputStream (); String str = "Welcome to login to the server server!"; os.write (str.getBytes ()); / / close the file stream os.close (); br.close (); is.close () Socket.close (); server.close ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}
Client:
Public class SocketClient {public static void main (String [] args) {try {/ * * 1, create socket Specify the address and port number of the server * 2, create a file stream * 3, perform a read or write operation * 4, close the file stream * 5, close socket * / System.out.println ("client started!") Socket socket = new Socket ("localhost", 8888); OutputStream os = socket.getOutputStream (); String msg = "user name: Zhang San password: 123123"; os.write (msg.getBytes ()); socket.shutdownOutput (); / / get server response information InputStream is = socket.getInputStream () BufferedReader br = new BufferedReader (new InputStreamReader (is)); String info = null; while ((info = br.readLine ())! = null) {System.out.println (info);} / / close resource br.close (); os.close (); is.close () Socket.close ();} catch (UnknownHostException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} example: data transfer based on TCP, transfer object
Server side:
Public class SocketServer {public static void main (String [] args) {try {/ * 1, create serverScoket object * 2, call accept () method to turn on listening * 3, get file stream (output stream or input stream) * 4, perform read and write operations * 5, close stream * 6, Close serversocket. * / ServerSocket server = new ServerSocket (8888); System.out.println ("Server started!") ; / / receive the message sent by the client Socket socket = server.accept (); InputStream is = socket.getInputStream (); / / deserialize ObjectInputStream ois = new ObjectInputStream (is); Student stu = (Student) ois.readObject (); stu.Show () / / write information to the client OutputStream os = socket.getOutputStream (); String str = "Welcome to login to the server server!"; os.write (str.getBytes ()); / / close the file stream ois.close (); os.close (); is.close () Socket.close (); server.close ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} catch (ClassNotFoundException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}
Client:
Public class SocketClient {public static void main (String [] args) {try {/ * * 1, create socket Specify the address and port number of the server * 2, create a file stream * 3, perform a read or write operation * 4, close the file stream * 5, close socket * / System.out.println ("client started!") Socket socket = new Socket ("localhost", 8888); OutputStream os = socket.getOutputStream (); / / create object Student stu = new Student (); stu.setName ("Zhang San"); stu.setPwd ("123123"); / / perform serialization operation ObjectOutputStream oos = new ObjectOutputStream (os) Oos.writeObject (stu); socket.shutdownOutput (); / / get server response information InputStream is = socket.getInputStream (); BufferedReader br = new BufferedReader (new InputStreamReader (is)); String info = null While ((info = br.readLine ())! = null) {System.out.println (info);} / / close the resource br.close (); is.close (); oos.close (); os.close (); socket.close () } catch (UnknownHostException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} example: based on multithreaded communication requests, multiple clients access the server
Server side:
Public class SocketServer {public static void main (String [] args) {try {/ * * 1, create serverScoket object 2, call the accept () method to turn on listening 3, get the file stream (output stream or input stream) 4, perform read and write operations * 5, close stream 6, close serversocket. * / ServerSocket server = new ServerSocket (8888); System.out.println ("Server started!") ; / / receive the message from the client while (true) {/ / blocking will cause the program to stop Socket socket = server.accept (); ServerThread st = new ServerThread (socket); st.start () Catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}
Thread class:
Public class ServerThread extends Thread {private Socket socket; public ServerThread (Socket socket) {this.socket = socket;} public void run () {InputStream is; try {is = socket.getInputStream (); / / deserialize ObjectInputStream ois = new ObjectInputStream (is); Student stu = (Student) ois.readObject (); stu.Show () / / write information to the client OutputStream os = socket.getOutputStream (); String str = "Welcome to login to the server server!"; os.write (str.getBytes ()); / / close the file stream os.close (); ois.close (); is.close () Socket.close ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} catch (ClassNotFoundException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}
Client:
Public class SocketClient {public static void main (String [] args) {try {/ * * 1, create socket Specify the address and port number of the server * 2, create a file stream * 3, perform a read or write operation * 4, close the file stream * 5, close socket * / System.out.println ("client started!") Socket socket = new Socket ("localhost", 8888); OutputStream os = socket.getOutputStream (); / / create object Student stu = new Student (); stu.setName ("Zhang San"); stu.setPwd ("123123"); / / perform serialization operation ObjectOutputStream oos = new ObjectOutputStream (os) Oos.writeObject (stu); socket.shutdownOutput (); / / get server response information InputStream is = socket.getInputStream (); BufferedReader br = new BufferedReader (new InputStreamReader (is)); String info = null While ((info = br.readLine ())! = null) {System.out.println (info);} / / close the resource br.close (); is.close (); oos.close (); os.close (); socket.close () } catch (UnknownHostException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} example: data transfer based on UDP
Server:
Public class SocketServer {public static void main (String [] args) {try {byte [] bytes = new byte [1024]; / / create a package object DatagramPacket packet = new DatagramPacket (bytes, bytes.length); / / create a socket object DatagramSocket socket = new DatagramSocket (8888) / / receive the message socket.receive (packet); / / convert the byte array to the string String msg = new String (packet.getData (), 0, packet.getLength ()); / / output the client's IP address and message System.out.println (packet.getAddress (). GetHostAddress () + ":" + msg) Socket.close ();} catch (SocketException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}
Client:
Public class SocketClient {public static void main (String [] args) {try {/ / define the message to be sent String msg = "user name: Zhang San password: 123"; / / get the address of the server InetAddress add = InetAddress.getByName ("localhost") / / create a packet package object that encapsulates the packet data to be sent and the server address and port number DatagramPacket packet = new DatagramPacket (msg.getBytes (), msg.getBytes (). Length, add, 8888); / / create a Socket object DatagramSocket socket = new DatagramSocket () / / send messages to server socket.send (packet); / / close socket socket.close ();} catch (UnknownHostException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} catch (SocketException e) {/ / TODO Auto-generated catch block e.printStackTrace () } catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} above is all the content of the article "sample Analysis of Scoket programming based on Java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.