Java implementation of a hello / hi simple network chat program

Using Java Socket connection between the client and the server, the client realize the function repeatedly transmitting the data to the server. That is, the user can continue typing in the console, one by one and sends the content to the server. And displayed on the server.

socket defined

        Two programs on the network via a bidirectional communication to realize the exchange of data, called the connection end of a socket.
Establishing a network communications connection to the at least one pair of port number (socket). socket is essentially a programming interface (API), for TCP / IP encapsulation, TCP / IP also provides an interface for programmers to do web development used, this is the Socket programming interface; HTTP is a sedan, provides a packaging or display data specific forms; the Socket engine, provides the ability to network communications.
        English Socket original meaning is "hole" or "socket." As BSD UNIX process communication mechanism, after taking one meaning. Commonly referred to as "socket" is used to describe IP address and port, a communication link is the handle can be used to enable communication between different virtual machine or on different computers. Hosts on the Internet generally running multiple software services, while providing several services. Each service will open a Socket, and bind to a port, different port corresponding to the different services. Socket as its original meaning as the English, like a porous outlet. If a host socket covered with a variety of rooms, each socket has a serial number, some outlets provide 220 volts AC, and some provide 110 volts AC, while others provide cable programming. The client software will plug into the socket different numbers, you can get different services.
        In simple terms, we have those data on the network can be seen in the water pipe that water, now is the waterworks server and the client is your own home, that set up outside of those pipes is fiber optics, telephone lines, etc. spread media network signal can now be directly stabbed with a broken water pipe to the water plant, and then stabbed the other end directly to your home it again ?? this is certainly not, or I do not want to water when the water is still filling Kill, not just stealing home, so this time the water you want the water to get past need to be a water valve and then flow through the valve control ah, etc., of your own home also installed a valve to control, or water fee ye count ah, ha ha ha

        Socket communication model:

 

 Program to achieve the following:

Client:

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


public  class Customer {

    public static void main(String[] args) {

        Socket the Socket = null ; // server socket linked 
        Scanner to fromKey = null ; // keyboard input stream 
        Scanner the fromServer = null ; // Get the byte stream sent by the server 
        the PrintWriter toServer = null ; // sends the server a word throttling

        the try {
             // linked server socket 
            Socket = new new the Socket ( "localhost", 8866 );

            /*
             * Note: the server and the client does not have to get the input stream, this will lead to blocking socket
             * * / 
            // byte stream read from the server instance of 
            the fromServer = new new Scanner (Socket.getInputStream ());
             // instantiate server to write the byte stream 
            toServer = new new the PrintWriter (Socket.getOutputStream ());
             / / instantiation keyboard input stream 
            to fromKey = new new Scanner (the System.in);

            the while (fromServer.hasNextLine ()) {
                 // blocked waiting for the server to send a message 
                String fromServerData = fromServer.nextLine ();
                System.out.println ( "Server:" + fromServerData);
                System.out.print ( "I (client):" );
                 // get the input data 
                String toServerData = fromKey.nextLine ();
                 // sent to the server 
                toServer.println (toServerData);
                toServer.flush();
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                fromServer.close();
                toServer.close();
                socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


    }

}

Server:

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {

    public static void main(String[] args) {

        The ServerSocket the ServerSocket = null ; // open socket 
        the Socket Socket = null ; // linked client socket 
        Scanner to fromKey = null ; // keyboard input stream 
        Scanner fromClient = null ; // Get byte read from the client stream 
        PrintWriter toClient = null ; // get the client to write to the byte stream

        try {
            ServerSocket = new ServerSocket(8866);
            System.out.println ( "Server has started, wait for client connections" );
             // link client socket 
            socket = ServerSocket.accept ();

            // instantiate write byte stream to the client 
            toClient = new new the PrintWriter (Socket.getOutputStream ());
            toClient.println ( "Hello client !!!" );
            toClient.flush();
            System.out.println ( "I (server): Client Hello !!!" );
             / *
             * Note: the server and the client does not have to get the input stream, this will lead to blocking socket
             * * / 
            // example byte stream read from the server 
            fromClient = new new Scanner (Socket.getInputStream ());
             // instantiate keyboard input stream 
            to fromKey = new new Scanner (the System.in);

            // blocked waiting for the client that sent 
            the while (fromClient.hasNextLine ()) {
                String fromClientData = fromClient.nextLine();
                System.out.println ( "Client:" + fromClientData);
                System.out.print ( "I (server-side):" );
                 // get the input data 
                String toClientData = fromKey.nextLine ();
                 // sent to the client 
                toClient.println (toClientData);
                toClient.flush();
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                fromClient.close();
                toClient.close();
                socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


    }

}

Socket API communication process and full resolution

 udp and TCP socket communication process is basically the same, the configuration is not the same as the incoming call when only api, to TCP client / server model as an example to look at the whole process.

 

1. socket()

  #include <sys/types.h>          /* See NOTES */
       #include <sys/socket.h>
       int socket(int domain, int type, int protocol);
    
    - Parameter Description
    domain: The two sides set socket communications protocol domain, local / internet ip4 or ip6
       Name                Purpose                          Man page
       AF_UNIX, AF_LOCAL   Local communication              unix(7)
       AF_INET IPv4 Internet protocols ip (7)
       AF_INET6 IPv6 Internet protocols ipv6 (7)

    type: type of socket set, commonly used
        SOCK_STREAM - generally corresponding to TCP, sctp
        SOCK_DGRAM - generally corresponds UDP
        SOCK_RAW - 
        
    protocol: setting a transport layer protocol used to communicate
    Common protocols have IPPROTO_TCP, IPPTOTO_UDP, IPPROTO_SCTP, IPPROTO_TIPC, etc., can be set to 0, the system of their choice. Note that protocol and type are not random combinations.

  socket () API is implemented in glibc, the function call to turn the sys_socket kernel (), as the call chain.

     

        Detailed kernel realize I do not have to read, generally understood. Call socket () allocates memory in kernel space and save the related configuration. While the association will this kernel memory and file system, it would be possible to modify this configuration to access or read / write socket by filehandle. Socket operation like the operation of the same file, the phrase should be unix Everything file. The maximum number of filehandle presentation system is limited, / proc / sys / fs / file-max sets the maximum number of available filehandle. Of course, this is a linux configuration, you can change the method see Increasing at The Open File Number The descriptors of , someone did that 1.6 million connection.

2. bind()

#include <sys/types.h>          /* See NOTES */
   #include <sys/socket.h>
   int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
   
   Parameter Description
   sockfd: file handle before the socket () obtained
   addr: address binding, may be based IP address or a local file path machine
   addrlen: address length
   
   Function Description
   bind () socket communication address setting, if INADDR_ANY said interface server listens on all of the unit, if it is 127.0.0.1, said local process communication listener (also outside of the process does not take into ah).

3. listen()

 #include <sys/types.h>          /* See NOTES */
   #include <sys/socket.h>
   int listen(int sockfd, int backlog);
   
   Parameter Description
   sockfd: file handle before the socket () obtained
   backlog: Set server may simultaneously receive a maximum number of links, server connection process of the end there will be a queue, listen to set the length of the queue.
   
   Function Description
   listen () is used only for server-side, provided the length of the reception queue. If the queue is full, server end of the connection can be discarded or reply New client ECONNREFUSED.
   

4. accept()

 #include <sys/types.h>          /* See NOTES */
   #include <sys/socket.h>
   int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
   
   Parameter Description:
   addr: peer address
   addrlen: address length
   
   Function Description:
   accept () out from the first queue in a pending connection, and a new socket and returns.
   We called the new socket connected socket, different from the previous listening socket.
   connected socket server for subsequent data interaction with the client, listening socket to continue waiting for new connection.
   When the queue there is no connection, if the socket by fcntl () is set to O_NONBLOCK, accept () will not block, otherwise usually block.
    

Question: kernel is how to distinguish between listening socket and connected socket it? ? Although quintuple the two are not the same, kernel how to know which socket interact with APP? By analyzing the content, it is SYN or data? It is doubtful.

5. connect()

  #include <sys/types.h>          /* See NOTES */
   #include <sys/socket.h>
   int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
   
   Parameter Description:
   sockfd: socket marked filehandle
   addr: server-side address
   addrlen: address length
   
   Function Description:
   connect () for the establishment of bilateral connections.
   For TCP connections, connect () actually initiated the TCP three-way handshake, connect after a successful return to the TCP connection is established.  
   For UDP, since UDP is connectionless, Connect () can be used to specify the address of the communication terminal, send subsequent data send () you do not need to fill the address.
   UDP may be used of course not Connect (), the socket () established to specify the destination address () in sendto.

  

Guess you like

Origin www.cnblogs.com/sunxiangyang/p/12013397.html