Socket--A simple understanding of yourself

Source: Internet
Author: User
Tags sin

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 protocols: 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, Therefore, the arrival of the destination, the time to arrive at the destination and the correctness of the content is 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, connection-oriented protocol, before data transfer between sockets must establish a connection, so in TCP need to connect

Time.

2,TCP Transmission data size limit, once the connection is established, the sockets of both sides can be transmitted in a uniform format of large

Data.

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 strong vitality in network communication, for example, remote connection (Telnet) and file Transfer (FTP) all 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 inferior to UDP High .

2,UDP is simple to operate and requires less monitoring, so it is often used for client/server applications in decentralized systems with high LAN reliability. 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, based on Socket of the Java Network Programming

1, 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.

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

    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 }}}
Client Code

   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 }}}
Server-Side

Socket--A simple understanding of yourself

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.