Java development of the socket programming detailed

Source: Internet
Author: User
Tags sin

This article is a detailed description of socket programming from 3 aspects:

One, the two main problems in network programming

Second, two types of transmission protocol: TCP;UDP

Third, socket-based Java network programming

One, the 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 transfer data when the host is found.

In the TCP/IP protocol, it is mainly responsible for the location of the network host, the routing of data transmission, and the IP address can uniquely determine a host on the Internet. The TCP layer provides an application-oriented reliable (TCP) or unreliable (UDP) data transmission mechanism, which is the main object of network programming, and generally does not need to care about how the IP layer handles the data.

At present, the popular network programming model is the client/server (c/s) structure. That is, both sides of the communication are waiting for the client to request and respond as a server. The customer requests the server when the service is required. Server generally as a daemon always run, listen to the network port, once a customer request, will start a service process to respond to the customer, while continuing to monitor the service port, so that later customers can also be timely service.

two, two types of transport protocol: TCP;UDP

TCP is the short name of Tranfer Control protocol and 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 the abbreviation of User Datagram protocol, is a non-connected 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 are not guaranteed.

Comparison:

Udp:

1, the full address information is given in each datagram, so there is no need to establish a connection between the sender and the receiver.

2,UDP Transmission of data is limited by size, each transmitted datagram must be limited to 64KB.

3,UDP is an unreliable protocol in which datagrams sent by the sender do not necessarily reach the receiver in the same order

Tcp:

1, the connection-oriented protocol, before the data transmission between the socket must establish a connection, so in TCP requires connection time.

2,TCP Transmission data size limit, once the connection is established, the socket on both sides can transfer large data in a uniform format.

3,TCP is a reliable protocol that ensures that the receiver is fully and correctly getting all the data sent by the sender.

Application:

1,tcp has a strong vitality in network communications, such as remote Connection (Telnet) and file Transfer (FTP), which require the data to be reliably transmitted over an indefinite length. 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, socket-based Java network programming1, what is a socket

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. Sockets are typically used to connect clients and service parties. Sockets are a very popular programming interface for the TCP/IP protocol, and a socket is uniquely determined by an IP address and a port number. However, the type of protocol supported by the 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.

The process of 2,socket communication

Server side Listen (listening) a port has a connection request, the client sends a connect request to the server side, and the server sends back the Accept message to the client side. A connection is built up. Both the server side and client side can communicate with each other through methods such as Send,write.

For a full-featured socket, the following basic structure is included, and the work process consists of the following four basic steps:

(1) Create socket;

(2) Open the input/output stream connected to the socket;

(3) Read/write the socket according to certain protocol;

(4) Close the socket. (In practice, the displayed close is not used, although many articles recommend this, but in my program, it may be because the program itself is relatively simple, the requirements are not high, so there is no impact.) )

3, create socket

Create socket

Java provides two classes of sockets and ServerSocket in Package java.net, respectively, to represent the client and server side of a two-way connection. This is a two well-packaged class that is very handy to use. The method is constructed 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, hostname, and port number of the other side of the two-way connection, stream indicates whether the socket is a stream socket or datagram Socket,localport represents the port number of the local host, LOCALADDR and BINDADDR is the address of the local machine (ServerSocket's host address), 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. For example: Learning video Network http://www.xxspw.com

Socket client = new socket ("127.0.01.", 80);

ServerSocket Server = new ServerSocket (80);

Note that you must be careful when choosing a port. 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.

If an error occurs when creating the socket, IOException will be generated and must be handled in the program. So when creating sockets or ServerSocket, you must catch or throw exceptions.

4, Simple Client/server program

1. Client programs

ImportJava.io.*;Importjava.net.*; Public classtalkclient { Public Static voidMain (String args[]) {Try{Socket Socket=NewSocket ("127.0.0.1", 4700); //make a customer request to port 4700 on this machineBufferedReader sin=NewBufferedReader (NewInputStreamReader (system.in)); //constructing BufferedReader objects from System standard input devicesprintwriter os=NewPrintWriter (Socket.getoutputstream ()); //The output stream is obtained by the socket object, and the PrintWriter object is constructedBufferedReader is=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); //The input stream is obtained by the socket object and the corresponding BufferedReader object is constructedString ReadLine; ReadLine=sin.readline ();//reads a string from the system standard input             while(!readline.equals ("Bye")){                //stop Looping if the string read in from standard input is "bye"os.println (ReadLine); //output A string read from the system standard input to the serverOs.flush (); //refreshes the output stream so that the server receives the string immediatelySystem.out.println ("Client:" +ReadLine); //Print the Read-in string on the system standard outputSystem.out.println ("Server:" +is.readline ()); //reads a string from the server and prints it to the standard outputReadLine=sin.readline ();//reads a string from the system standard input            } //Continue loopingos.close ();//close the socket output streamis.close ();//close the socket input streamsocket.close ();//Close Socket        } Catch(Exception e) {System.out.println ("Error" +e);//Error, print error message        }    }}

2. Server-side Programs

ImportJava.io.*;Importjava.net.*;ImportJava.applet.Applet; Public classTalkserver { Public Static voidMain (String args[]) {Try{serversocket server=NULL; Try{Server=NewServerSocket (4700); //Create a ServerSocket to listen for customer requests on port 4700            } Catch(Exception e) {System.out.println ("Can not listen to:" +e); //error, printing error message} socket Socket=NULL; Try{Socket=server.accept (); //use the Accept () block to wait for a customer request, a customer//When the request arrives, a socket object is generated and the execution continues            } Catch(Exception e) {System.out.println ("Error." +e); //error, printing error message} String Line; BufferedReader is=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); //The input stream is obtained by the socket object and the corresponding BufferedReader object is constructedprintwriter os=Newprintwriter (Socket.getoutputstream ()); //The output stream is obtained by the socket object, and the PrintWriter object is constructedBufferedReader sin=NewBufferedReader (NewInputStreamReader (system.in)); //constructing BufferedReader objects from System standard input devicesSystem.out.println ("Client:" +is.readline ()); //print a string read from the client on standard output Line=Sin.readline (); //reads a string from a standard input         while(!line.equals ("Bye")) {            //If the string is "Bye", the loop is stoppedos.println (line); //output The string to the clientOs.flush (); //refreshes the output stream so that the client receives the string immediatelySystem.out.println ("Server:" +Line ); //Print the Read-in string on the system standard outputSystem.out.println ("Client:" +is.readline ()); //reads a string from the client and prints it to the standard output Line=Sin.readline (); //reads a string from the system standard input        } //Continue loopingos.close ();//close the socket output streamis.close ();//close the socket input streamsocket.close ();//Close Socketserver.close ();//Close ServerSocket        } Catch(Exception e) {System.out.println ("Error:" +e); //error, printing error message        }    }}

5, support multi-client Client/server program

The previous Client/server program can only implement a conversation between the server and a client. In practice, it is often a permanent program running on the server that can receive requests from multiple clients and provide the appropriate services. In order to realize the function of serving multiple customers in the server side, the above program needs to be reformed and multi-client mechanism can be realized by multithreading. The server always listens for customer requests on the specified port, and once it listens to a customer request, the server initiates a dedicated service thread to respond to the customer's request, and the server itself enters the listening state immediately after the thread is started, waiting for the next customer to arrive.

Java development of the socket programming detailed

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.