Java Socket Network Programming practice

Source: Internet
Author: User

transferred from: Http://my.oschina.net/leejun2005/blog/104955#comments one, TCP/IP protocol

Since it is network programming, involving the interaction between several systems, the first thing to consider is how to accurately locate one or several hosts on the network, and the other is how to carry out reliable and efficient data transmission. This will use the TCP/IP protocol.

TCP/IP (Transmission Control Protocol) consists of the IP protocol of the network layer and the TCP protocol of the Transport layer. The IP layer is responsible for the location of the network host, the routing of Data transmission, the IP address can uniquely determine a host on the Internet. The TCP layer is responsible for the application-oriented reliable or unreliable data transmission mechanism, which is the main object of network programming.

second, TCP and UDP

TCP is a connection-oriented protocol that guarantees reliable transmission. With the TCP protocol transmission, a sequential error-free data stream is obtained. A connection must be established between the sender and the receiver's paired two sockets to communicate on the basis of the TCP protocol, and when a socket (usually a server socket) waits for a connection, the other socket can require a connection. Once the two sockets are connected, they can carry out two-way data transfer and both can send or receive operations.

UDP is a non-connection-oriented protocol, each datagram is a separate information, including the full source address or destination address, it on the network with any possible path to the destination, so can reach the destination, the time to reach the destination and the correctness of the content is not guaranteed.

TCP and UDP differences:

TCP Features:

1, TCP is a connection-oriented protocol, through three handshake to establish a connection, communication is completed to remove the connection, because TCP is a connection-oriented protocol, so it can only be used for point-to-point communication. and establishing a connection also consumes time and overhead.

2, TCP transmission data no size limit, for large data transmission.

3, TCP is a reliable protocol, it can ensure that the receiver can complete and correctly receive all the data sent by the sender.

UDP Features:

1, UDP is a non-connected communication protocol, UDP data includes the destination port number and the source port number information, because the communication does not need to connect, so it can achieve broadcast transmission.

2, UDP transmission of data has a size limit, each transmitted datagram must be limited to 64KB within.

3, UDP is an unreliable protocol, the sender sends the datagram is not necessarily in the same order to reach the receiving party.

TCP and UDP applications:

1. TCP has strong vitality in network communication, such as remote Connection (Telnet) and file Transfer (FTP), which require the data of indefinite length to be transmitted reliably. But reliable transmission is to pay a price, the correctness of the data content of the test must occupy the computer processing time and network bandwidth, so the efficiency of TCP transmission is not as high as UDP.

2,UDP is simple to operate and requires less monitoring, so it is often used in client/server applications in decentralized systems with high reliability for LANs. For example, the video conferencing system, does not require audio and video data is absolutely correct, as long as the consistency can be guaranteed, in this case, it is obvious that using UDP is more reasonable.

third, what is the socket

Sockets are also commonly referred to as "sockets," which describe IP addresses and ports, and are a handle to a communication chain. The two programs on the network realize the exchange of data through a two-way communication connection, one end of this bidirectional link is called a socket, and a socket is determined only by an IP address and a port number. Applications typically make requests to the network through sockets or answer network requests. Socket is a very popular programming interface of TCP/IP protocol, but the type of protocol supported by socket is not only TCP/IP, so there is no necessary connection between the two. In the Java environment, socket programming mainly refers to the network programming based on TCP/IP protocol.

Socket communication process: The server listens to a port for a connection request, the client sends a connection request to the server, and the server receives a connection request to send a message to the client, so that a connection is set up. Both the client and the server can communicate with each other by sending messages to each other.

The basic working procedure of a socket consists of the following four steps:

1, create sockets;

2. Open the input/output stream connected to the socket;

3, in accordance with a certain protocol to read and write socket sockets;

4. Close the socket.

iv. socket in Java

There are two classes under the Java.net package: Sockets and ServerSocket. ServerSocket is used for server-side, socket is used when establishing network connection. When the connection succeeds, a socket instance is generated at both ends of the application, manipulating the instance to complete the required session. For a network connection, sockets are equal, and there is no difference, not due to different levels on the server side or on the client. Either the socket or the ServerSocket their work is done through the SocketImpl class and its subclasses.

Lists a few common construction methods:

Socket (inetaddress address,int port);//Creates a stream socket and connects it to the specified port number for the specified IP address socket (String host,int port);//Creates a stream socket and connects it to the specified port number on the specified host socket (inetaddress address,int port, InetAddress localaddr,int localport);//Creates a socket and connects it to the specified remote port on the specified remote address socket (String host,int port, InetAddress localaddr,int localport); // Create a socket and connect it to the specified remote port on the specified remote host socket (SocketImpl impl);  creates an SocketImpl Socket serversocket (int port) using the user-specified. create a server socket bound to a specific port serversocket (int port,int backlog);  creates a server socket with the specified backlog and binds it to the specified local port number serversocket (int port,int backlog, inetaddress bindaddr);  creates a server with the specified port, the listener backlog, and the local IP address to bind to            

In the constructor parameter, address, host, and port are the IP address, hostname, and port number of the other side of the two-way connection, and stream indicates whether the socket is a stream socket or datagram Socket,localport the port number of the local host. Localaddr and BINDADDR are the address of the local machine (the host address of the ServerSocket), Impl is the parent of the socket and can be used to create serversocket and to create sockets. Count indicates the maximum number of connections that can be supported by the server.

Note: You must carefully select the port number. Each port provides a specific service, and only the correct port is given to obtain the appropriate service. The port number of the 0~1023 is reserved for the system, such as the port number of the HTTP service for the 80,telnet service port number is 23, so when we select the port number, it is best to select a number greater than 1023 to prevent a conflict.

Several important Socke methods are:

Public InputStream getInputStream (); the// method obtains the network connection input, and returns a Iutputstream object instance public OutputStream Getoutputstream ();  The other end of the method connection will get input and return a OutputStream object instance public Socket accept ();  used to generate "blocking" until a connection is accepted and a client's socket object instance is returned. 

"Blocking" is a term that causes a program to run temporarily "stuck" in this place until a session is generated, and then the program continues; usually "blocking" is generated by loops.

Note: Where both the getInputStream and Getoutputstream methods produce a ioexception, it must be captured because the stream object they return is usually used by another stream object.

Java Socket Network Programming practice

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.