Java based on socket implementation of network programming examples of detailed _java

Source: Internet
Author: User
Tags flush readline sin

One, two main problems in network programming

One is how to accurately locate the network on one or more hosts, and the other is to find the host after the reliable and efficient data transmission.

In the TCP/IP protocol, the IP layer is mainly 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 provides a reliable (TCP) or unreliable (UDP) data transmission mechanism for applications, 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 more popular network programming model is client/server (c/s) structure. That is, both sides of the communication wait for the customer to request and respond as a server. The customer applies to the server when the service is needed. The server is always running as a daemon, listening to the network port, once the customer request, will start a service process to ring should customers, while their own continue to monitor the service port, so that later customers can also be timely access to services.

Second, two types of transport protocol: TCP;UDP

TCP is Tranfer Control Protocol the short name, is a connection-oriented protocol to ensure reliable transmission. Through the TCP protocol transmission, obtains is a sequential error-free data stream. A connection must be established between the pair of two sockets of the sender and receiver to communicate on the basis of the TCP protocol, and when one socket (usually the server socket) waits for the connection to be made, another socket can require a connection. Once these two sockets are connected, they can transmit data in both directions, and both can send or receive operations.

UDP is User Datagram Protocol the abbreviation, is a connectionless protocol, each datagram is a separate information, including the full source address or destination address, it on the network on any possible path to the destination, so whether to reach the destination, the time to arrive at the destination and the correctness of the content is not guaranteed.

Comparison:

Udp:

    1. 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 transmits data with a size limit, and 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 protocols, which must be connected before the data is transmitted between sockets, so the connection time is required in TCP.
    2. TCP transmits data size limits, and once the connection is established, both sockets can transmit 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 great vitality in network communications, such as remote Connection (Telnet) and file Transfer (FTP) that require indefinite length of data to be transmitted reliably. But the reliable transmission is to pay the price, the test of the correctness of the data content must occupy the processing time of the computer and the bandwidth of the network, so the TCP transmission efficiency is not as high as UDP.
    2. UDP is simple and requires less monitoring, so it is usually used for client/server applications in decentralized systems with high reliability on the LAN. For example, video conferencing system, does not require audio and video data is absolutely correct, as long as the consistency can be guaranteed, in this case, the obvious use of UDP is more reasonable.

Three, Java network programming based on socket

1, what is socket

Two programs on the network realize the exchange of data through a two-way communication connection, one end of this two-way link is called a socket. The socket is typically used to implement a connection between the client and the service party. The socket is 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 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) whether a port has a connection request, the client sends a connect request to the server side, and the server sends back the Accept (accepted) message to the client side. A connection is established. Both the server end and the client side can communicate with each other by means of send,write.

For a fully functional socket, include the following basic structure, which includes the following four basic steps:

(1) Create socket;

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

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

(4) Close the socket. (In practice, not to use the display of closed, although many articles are recommended, but in my program, because the program itself is relatively simple, the requirements are not high, so did not cause any impact.) )

3, create the socket

 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 Addre

  SS, 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 addresses, hostname, and port number of the other side of the two-way connection, respectively. Stream indicates whether the socket is a stream socket or datagram socket,localport that represents the port number of the local host, LOCALADDR and BINDADDR are the addresses of the local machine (ServerSocket host address), Impl is the parent class of the socket, which can be used to create serversocket and to create a socket. Count indicates the maximum number of connections that the server can support.

  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 for the 0~1023 is reserved for the system, for example, the port number of the HTTP service is the port number of the 80,telnet service is 23, so when we select the port number, it is best to select a number greater than 1023 to prevent conflicts.

If an error occurs when the socket is created, a ioexception is generated and must be processed in the program. So in creating a socket or serversocket you have to catch or throw an exception.

4, Simple Client/server program

1. Client program

 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);

        Shanben 4700 Ports Issue customer request BufferedReader sin=new BufferedReader (New InputStreamReader (system.in));

        The BufferedReader object PrintWriter os=new printwriter (Socket.getoutputstream ()) is constructed by the system standard input device. The output stream is obtained from the socket object and the PrintWriter object is constructed BufferedReader is=new BufferedReader (New InputStreamReader (Socket.getinputstrea

        M ()));

        The input stream is obtained from the socket object and the corresponding BufferedReader object String ReadLine is constructed; Readline=sin.readline (); Read a string from System standard input while (!readline.equals ("Bye")) {//Stop looping OS.PRINTLN if the string read from standard input is "Bye" (Readlin

          e);

          The string read from the system standard input is output to the server Os.flush ();

          Refreshes the output stream so that the server immediately receives the string System.out.println ("Client:" +readline); Print read-in string System.out.println on system standard Output ("Server:" +is.readline ()); Reads a string from the server and prints it to the standard output readline=sin.readline (); Read a string from the system standard input///Resume loop os.close (); Close socket output stream is.close (); Close the socket input stream socket.close (); Close the socket}catch (Exception e) {System.out.println ("error" +e);//error, print error message}}

2. Server-side Programs

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 ServerSocket (4700);

        Create a serversocket on port 4700 to listen for client requests}catch (Exception e) {System.out.println ("Can not listen to:" +e);

        Error, print error message} Socket socket=null;

          try{socket=server.accept (); Using accept () blocking waits for a customer request, a client//request arrives with a socket object and continues execution}catch (Exception e) {System.out.println ("Error.")

          +E);

        Error, print error message} String line;

         BufferedReader is=new BufferedReader (New InputStreamReader (Socket.getinputstream ()));

         The input stream is obtained from the socket object and the corresponding BufferedReader object is constructed PrintWriter os=newprintwriter (Socket.getoutputstream ()); The output stream is obtained from the socket object and the PrintWriter object is constructed BufferedReader sin=new BufferedReader (new inputsTreamreader (system.in));

        The BufferedReader object System.out.println ("Client:" +is.readline ()) is constructed by the system standard input device;

        Print a string read from the client on standard output line=sin.readline ();

          Reads a string from standard input while (!line.equals ("Bye")) {//If the string is "Bye", stops looping os.println (line);

          Output the string Os.flush () to the client;

          Refreshes the output stream so that the client immediately receives the string System.out.println ("Server:" +line);

          Print the Read string System.out.println on the system standard output ("Client:" +is.readline ());

          Read a string from the client and print to the standard output line=sin.readline (); Read a string from the system standard input///Resume loop os.close (); Close socket output stream is.close (); Close the socket input stream socket.close (); Close socket Server.close ();

        Close ServerSocket}catch (Exception e) {System.out.println ("Error:" +e); Error, print error message}}

5, support multi-customer Client/server program

The previous Client/server program can only implement a conversation between a server and a customer. In practice, a permanent program is often run on a server that can receive requests from multiple clients and provide the appropriate services. In order to realize the function of providing service to multiple customers in server, the above program needs to be reformed, and multi-client mechanism is realized by multithreading. The server always listens for client requests on the specified port, and once the client requests are tapped, 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.

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.