Java: Socket programming learning Summary

Source: Internet
Author: User

I. 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 transmit data reliably and efficiently after finding the hosts.
In TCP/IP, the IP layer is mainly responsible for locating network hosts and routing data transmission. The IP address can uniquely identify a host on the Internet. The TCP layer provides an application-oriented reliable (tcp) or non-reliable (UDP) data transmission mechanism, which is the main object of network programming, generally, you do not need to care about how the IP layer processes data.
Currently, the popular network programming model is the Client/Server (C/S) structure. That is, one Party serves as the server to wait for the customer to make a request and respond. The customer submits an application to the server when the service is required. The server is always running as a daemon and listens to the network port. Once a customer requests the server, a service process is started to respond to the customer. At the same time, the server continues to listen to the Service port, so that later customers can get services in a timely manner.


Ii. Two types of transmission protocols: TCP and UDP

TCP is short for Tranfer Control Protocol. It is a connection-oriented Protocol that ensures reliable transmission. It is transmitted over TCP to obtain a sequential error-free data stream. The sender and receiver must establish a connection between two pairs of sockets to facilitate communication based on the TCP protocol. When a socket (usually a server socket) is waiting to establish a connection, another socket can require a connection. Once the two sockets are connected, they can perform bidirectional data transmission, and both parties can send or receive data.
UDP is short for User datasync Protocol. It is a connectionless Protocol. Each Datagram is an independent information, including the complete source address or destination address, it is transmitted to the destination in any possible path on the network. Therefore, the correctness of the arrival time, arrival time, and content cannot be guaranteed.
Comparison:
UDP:
The complete address information is provided in each datagram, so there is no need to establish a connection between the sender and the receiver.
There is a limit on the size of UDP data transmission. Each transmitted datagram must be within 64 KB.
UDP is an unreliable protocol. The data packets sent by the sender do not necessarily arrive at the receiver in the same order.
TCP:
For connection-oriented protocols, a connection must be established before data transmission between sockets. Therefore, the connection time is required in TCP.
The data size limit of TCP transmission. Once the connection is established, the sockets of both parties can transmit big data in a unified format.
TCP is a reliable protocol that ensures that the receiver fully and correctly obtains all data sent by the sender.
Application:
1. TCP has a strong vitality in network communication. For example, remote connection (Telnet) and file transmission (FTP) require data of an indefinite length to be reliably transmitted. However, reliable transmission requires a price. The test of the correctness of the data content will inevitably take up the processing time of the computer and the bandwidth of the network. Therefore, the efficiency of TCP transmission is not as high as that of UDP.
2. UDP is easy to operate and requires less monitoring. Therefore, it is usually used for client/server applications in distributed systems with high LAN reliability. For example, a video conferencing system does not require that the audio and video data be absolutely correct. You only need to ensure consistency. In this case, UDP is obviously more reasonable.


Iii. Socket-based java Network Programming

1. What is Socket?
Two programs on the network exchange data through a two-way communication connection. one end of this two-way link is called a Socket. Socket is usually used to connect the customer and the service provider. Socket is a very popular programming interface of TCP/IP protocol. A Socket is uniquely identified by an IP address and a port number.
However, the Protocol types supported by the Socket are not only TCP/IP, so there is no necessary link between the two. In the Java environment, Socket programming mainly refers to network programming based on TCP/IP protocol.
2. Socket Communication Process
Server Listen (listener) whether a port has a connection request. The Client sends a Connect (connection) request to the Server, and the Server sends an Accept (Accept) message back to the Client. A connection is established. Both the Server and Client can communicate with each other by sending, writing, and other methods.
For a fully functional Socket, it must contain the following basic structure. The working process includes the following four basic steps:
(1) create a Socket;
(2) Open the input/output stream connected to the Socket;
(3) perform read/write operations on the Socket according to certain protocols;
(4) Disable Socket. (display close is not used in practical applications. Although this is recommended in many articles, in my program, it may be because the program itself is relatively simple and has low requirements, so nothing has caused an impact .)
3. Create a Socket
Java provides two types of Socket and ServerSocket in the java.net package, which are used to represent the client and server for two-way connection respectively. These are two encapsulated classes that are very convenient to use. The construction method is as follows:
  
[Java]
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, intlocalPort)
ServerSocket (int port );
ServerSocket (int port, int backlog );
ServerSocket (int port, int backlog, InetAddress bindAddr)

Here, address, host, and port are the IP address, host name, and port number of the other side of the two-way connection. stream indicates whether the socket is a stream socket or a datagram socket. localPort indicates the port number of the local host, localAddr and bindAddr are the addresses of local machines (the host address of ServerSocket), and impl is the parent class of socket, which can be used to create both serverSocket and Socket. Count indicates the maximum number of connections supported by the server. For example:
[Java]
Socket client = new Socket ("127.0.01.", 80 );
ServerSocket server = new ServerSocket (80 );
Note: Be careful when selecting a port. Each port provides a specific service. Only the correct port is provided to obtain the corresponding service. 0 ~ The port number of 1023 is retained by the system. For example, the port number of the http service is 80, the port number of the telnet service is 21, and the port number of the ftp service is 23, it is best to select a number greater than 1023 to prevent conflicts.
If an error occurs during socket creation, an IOException is generated and must be processed in the program. Therefore, exceptions must be caught or thrown when a Socket or ServerSocket is created.


4. Simple Client/Server programs

1. Client Program
 
[Java]
Import java. io .*;
Import java.net .*;
Public class TalkClient {
Public static void main (String args []) {
Try {
Socket socket = new Socket ("127.0.0.1", 4700 );
// Send a customer request to port 4700 of the Local Machine
BufferedReader sin = new BufferedReader (new InputStreamReader (System. in ));
// The BufferedReader object is constructed by the system standard input device.
PrintWriter OS = new PrintWriter (socket. getOutputStream ());
// Obtain the output stream from the Socket object and construct the PrintWriter object
BufferedReader is = new BufferedReader (newInputStreamReader (socket. getInputStream ()));
// Obtain the input stream from the Socket object and construct the corresponding BufferedReader object
String readline;
Readline = sin. readLine (); // read a string from the system standard input
While (! Readline. equals ("bye ")){
// If the string read from the standard input is "bye", the loop is stopped.
OS. println (readline );
// Output the string read from the system standard input to the Server
OS. flush ();
// Refresh the output stream so that the Server receives the string immediately
System. out. println ("Client:" + readline );
// Print the read string on the system standard output
System. out. println ("Server:" + is. readLine ());
// Read a string from the Server and print it to the standard output.
Readline = sin. readLine (); // read a string from the system standard input
} // Continue the loop
OS. close (); // close the Socket output stream
Is. close (); // close the Socket input stream
Socket. close (); // close the Socket
} Catch (Exception e ){
System. out. println ("Error" + e); // the Error message is printed.
}
}
}

2. server programs
  
[Java]
Import java. io .*;
Import java.net .*;
Import java. applet. Applet;
Public class TalkServer {
Public static void main (String args []) {
Try {
ServerSocket server = null;
Try {
Server = new serversockets (4700 );
// Create a ServerSocket to listen to customer requests on port 4700
} Catch (Exception e ){
System. out. println ("can not listen to:" + e );
// Error: print error message
}
Socket socket = null;
Try {
Socket = server. accept ();
// Use accept () to block waiting for customer requests.
// When the request arrives, a Socket object is generated and the execution continues.
} Catch (Exception e ){
System. out. println ("Error." + e );
// Error: print error message
}
String line;
BufferedReader is = new BufferedReader (newInputStreamReader (socket. getInputStream ()));
// Obtain the input stream from the Socket object and construct the corresponding BufferedReader object
PrintWriter OS = newPrintWriter (socket. getOutputStream ());
// Obtain the output stream from the Socket object and construct the PrintWriter object
BufferedReader sin = new BufferedReader (new InputStreamReader (System. in ));
// The BufferedReader object is constructed by the system standard input device.
System. out. println ("Client:" + is. readLine ());
// Print the string read from the client on the standard output
Line = sin. readLine ();
// Read a string from the standard input
While (! Line. equals ("bye ")){
// If the string is "bye", the loop is stopped.
OS. println (line );
// Output the string to the client
OS. flush ();
// Refresh the output stream so that the Client receives the string immediately
System. out. println ("Server:" + line );
// Print the read string on the system standard output
System. out. println ("Client:" + is. readLine ());
// Read a string from the Client and print it to the standard output.
Line = sin. readLine ();
// Read a string from the system standard input
} // Continue the loop
OS. close (); // close the Socket output stream
Is. close (); // close the Socket input stream
Socket. close (); // close the Socket
Server. close (); // close ServerSocket
} Catch (Exception e ){
System. out. println ("Error:" + e );
// Error: print error message
}
}
}

Related Article

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.