Java (Socket programming basics), socket programming Basics

Source: Internet
Author: User

Java (Socket programming basics), socket programming Basics
I,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 transmit data reliably and efficiently after finding the hosts.

In TCP/IP, the IP layer is mainly responsible for locating network hosts and routing data transmission. The IP address can uniquely identify a host on the Internet.

The TCP layer provides an application-oriented reliable (tcp) or non-reliable (UDP) data transmission mechanism, which is the main object of network programming, generally, you do not need to care about how the IP layer processes data.

Currently, the popular network programming model is the Client/Server (C/S) structure. That is, one Party serves as the server to wait for the customer to make a request and respond. The customer submits an application to the server when the service is required. The server is always running as a daemon and listens to the network port. Once a customer requests the server, a service process is started to respond to the customer. At the same time, the server continues to listen to the Service port, so that later customers can get services in time

II, Two types of transmission protocols: TCP And UDP

TCPYesTranfer Control ProtocolIs a connection-oriented protocol for reliable transmission. It is transmitted over TCP to obtain a sequential error-free data stream. The sender and receiver must establish a connection between two pairs of sockets to facilitate communication based on the TCP protocol. When a socket (usually a server socket) is waiting to establish a connection, another socket can require a connection. Once the two sockets are connected, they can perform bidirectional data transmission, and both parties can send or receive data.

UDPYesUser datasync ProtocolThe abbreviation is a connectionless protocol. Each datagram is an independent information, including the complete source address or destination address. It is transmitted to the destination in any possible path on the network, therefore, whether or not to reach the destination, the time to arrive at the destination, and the correctness of the content cannot be guaranteed.

  

Difference Between TCP and UDP:

UDP:

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

2. When UDP transmits dataYesThe size of each transmitted datagram must be limited64KBWithin.

3. UDP is an unreliable protocol. The data packets sent by the sender do not necessarily arrive at the receiver in the same order.

TCP:

1. For connection-oriented protocols, a connection must be established before data transmission between sockets. Therefore, the connection time is required in TCP.

2. TCP transmission data size limit. Once the connection is established, the sockets of both parties can transmit big data in a unified format.

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

Application:

1,TCPStrong vitality in network communication, such as remote connection (Telnet) and file transmission (FTP) require data of an indefinite length to be reliably transmitted. However, reliable transmission requires a price. The test of the correctness of data content must take up the processing time and bandwidth of the computer,ThereforeTCPTransmittedEfficiencyWorseUDPHigh.

2,UDPIt is easy to operate and requires less monitoring. Therefore, it is usually used for client/server applications in distributed systems with high LAN reliability. For example, a video conferencing system does not require that the audio and video data be absolutely correct. You only need to ensure consistency. In this case, UDP is obviously more reasonable.

 

III, Socket-based java Network Programming 1. What is Socket?

Two programs on the network exchange data through a two-way communication connection. one end of this two-way link is called a Socket. Socket is usually used to connect the customer and the service provider. Socket is a very popular programming interface of TCP/IP protocol. A Socket is uniquely identified by an IP address and a port number.

However, the Protocol types supported by the Socket are not only TCP/IP, so there is no necessary link between the two. In the Java environment, Socket programming mainly refers to network programming based on TCP/IP protocol.

2. Socket Communication Process

Server Listen (listener) whether a port has a connection request. The Client sends a Connect (connection) request to the Server, and the Server sends an Accept (Accept) message back to the Client. A connection is established. Both the Server and Client can communicate with each other by sending, writing, and other methods.

For a fully functional Socket, it must contain the following basic structure. The working process includes the following four basic steps:

(1) create a Socket;

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

(3) perform read/write operations on the Socket according to certain protocols;

(4) Disable Socket. (display close is not used in practical applications. Although this is recommended in many articles, in my program, it may be because the program itself is relatively simple and has low requirements, so there is no impact .)


3. Socket Classification

Original socket (SOCK_RAW): This interface allows direct access to lower-level protocols, such as IP addresses, and can receive data frames and data packets on the local Nic, which is useful for network traffic monitoring and analysis.

Streaming socket (SOCK_STREAM): TCP provides a connection-oriented and reliable data transmission service, which can receive data in the order of sending without any errors or repeated sending.

Datagram socket (SOCK_DGRAM): UDP, no connection service, data reports are sent in the form of independent packets, no error guarantee is provided, data may be lost, or duplicated, and the receiving order is disordered.

4. Create a Socket

Create Socket

Java provides two types of Socket and ServerSocket in the java.net package, which are used to represent the client and server for two-way connection respectively. These are two encapsulated classes that are very convenient to use. The construction method is 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)

Here, address, host, and port are the IP address, host name, and port number of the other side of the two-way connection. stream indicates whether the socket is a stream socket or a datagram socket. localPort indicates the port number of the local host, localAddr and bindAddr are the addresses of local machines (the host address of ServerSocket), and impl is the parent class of socket, which can be used to create both serverSocket and Socket. Count indicates the maximum number of connections supported by the server. Example: learning video network http://www.xxspw.com

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

ServerSocket server = new ServerSocket (80 );

Note: Be careful when selecting a port. Each port provides a specific service. Only the correct port is provided to obtain the corresponding service. 0 ~ The port number of 1023 is retained by the system. For example, the port number of the http service is 80, the port number of the telnet service is 21, and the port number of the ftp service is 23, it is best to select a number greater than 1023 to prevent conflicts.

If an error occurs during socket creation, an IOException is generated and must be processed in the program. Therefore, exceptions must be caught or thrown when a Socket or ServerSocket is created.

Iv. Simple implementation (TCP/IP, streaming socket)

Entity class

package entity;

import java.io.Serializable;

/ **
 * User class
 *
 * /
public class User implements Serializable {
    
    private String name;
    private String password;
    
    
    public String getName () {
        return name;
    }
    public void setName (String name) {
        this.name = name;
    }
    public String getPassword () {
        return password;
    }
    public void setPassword (String password) {
        this.password = password;
    }
}
Client

package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import entity.User;

/ **
 * Client
 * Steps:
 * 1. Establish client Socket connection to specify server address and port
 * 2. Get Socket read stream
 * 3. Use stream to read and write Socket according to certain protocol
 * 4. Use close () to close the stream and socket
 *
 * /
public class LoginClient {

    public static void main (String [] args) {
        
        try {
            // 1. Establish a client socket connection, specify the server location and port
            Socket socket = new Socket ("localhost", 8800);
            // 2. Get Socket read and write stream
            OutputStream os = socket.getOutputStream ();
            ObjectOutputStream oos = new ObjectOutputStream (os);
            // 3. Use the stream to read and write the Socket with a certain protocol on time
            User user = new User ();
            user.setName ("Tom");
            user.setPassword ("123qwe");
            oos.writeObject (user);
    
            // Close the output stream
            socket.shutdownOutput ();
            
            // 4. Receive server response
            InputStream is = socket.getInputStream ();
            BufferedReader br = new BufferedReader (new InputStreamReader (is));
            String reply;
            while ((reply = br.readLine ())! = null) {
                System.out.println ("This is the client, the service response is:" + reply);
            }
            // 5. Close the resource
            br.close ();
            is.close ();
            oos.close ();
            os.close ();
            socket.close ();
        } catch (UnknownHostException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
        
        

    }

}
Server

package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import entity.User;

/ **
 * Server
 * Steps:
 * 1. Establish a ServerSocket to bind to the specified port and start listening
 * 2. Use the accept () method to block the waiting listening port and obtain a new connection
 * 3. Establish input stream and output stream
 * 4. Create a session on an existing agreement
 * 5. Use close () to close the stream and socket
 *
 * /
public class LoginServer {

    public static void main (String [] args) {

        try {
            // 1. Build a ServerScoket port for 8900
            ServerSocket serverScoket = new ServerSocket (8800);
            // 2. Use the accept method to listen to the port
            Socket socket = serverScoket.accept ();
            // 3. Get the input stream
            InputStream is = socket.getInputStream ();
            ObjectInputStream ois = new ObjectInputStream (is);
            // 4. Get user input information
            User user = (User) ois.readObject ();
            
                System.out.println ("This is the server, the user name is:" + user.getName () + "Password:" + user.getPassword ());

            OutputStream os = socket.getOutputStream ();
            PrintWriter pw = new PrintWriter (os);
            // 5. return information
            String reply = "Welcome,";
            pw.write (reply);
            pw.flush ();
            // 6. Close the resource
            pw.close ();
            os.close ();
            ois.close ();
            is.close ();
            socket.close ();
            serverScoket.close ();
        } catch (IOException e) {
            e.printStackTrace ();
        } catch (ClassNotFoundException e) {
            e.printStackTrace ();
        }

    }

}
 

Five, multi-threaded implementation (TCP / IP, streaming sockets)
Implementation class

package socket.object;

import java.io.Serializable;

/ **
 * User class
 * /
public class User implements Serializable {
    
    private String name;
    private String passowrd;
    private String sex;
    private String email;
    public String getName () {
        return name;
    }
    public void setName (String name) {
        this.name = name;
    }
    public String getPassowrd () {
        return passowrd;
    }
    public void setPassowrd (String passowrd) {
        this.passowrd = passowrd;
    }
    public String getSex () {
        return sex;
    }
    public void setSex (String sex) {
        this.sex = sex;
    }
    public String getEmail () {
        return email;
    }
    public void setEmail (String email) {
        this.email = email;
    }
    
    
}
Client

package socket.object;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class LoginClient {

    public static void main (String [] args) {

        try {
            // Create client Socket object
            Socket socket = new Socket ("localhost", 9200);
            // Get input and output streams
            ObjectOutputStream oos = new ObjectOutputStream (socket.getOutputStream ());
ObjectInputStream ois = new ObjectInputStream (socket.getInputStream ());
            
            User user = new User ();
            user.setName ("Jack");
            user.setPassowrd ("123456");
            user.setSex ("Male");
            user.setEmail ("Jack@qq.com");
            oos.writeObject (user);
            
            // Close the output stream
            //socket.shutdownOutput ();
            
            // Receive server response
            Object info = ois.readObject ();
            System.out.println ("Here is the client: the response of the service is:" + info.toString ());
            // Close the stream
            ois.close ();
            oos.close ();
            socket.close ();
        } catch (UnknownHostException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        } catch (ClassNotFoundException e) {
            e.printStackTrace ();
        }

    }

}
Server

package socket.object;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class LoginServer {

    public static void main (String [] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        
        try {
            // Create ServerSocket and specify the port
             serverSocket = new ServerSocket (9200);
            // Current connection number
             int nums = 0;
             // The server has been monitoring the status
             while (true) {
                // Use the accept method to listen to the port
                 socket = serverSocket.accept ();
                 // Each visit generates a thread
                 ServerThread serverThread = new ServerThread (socket);
                 // Start thread
                 serverThread.start ();
                 nums ++;
                 System.out.println ("The current number of customers is:" + nums);
                 // Get the customer's IP and host name
                 InetAddress ia = socket.getInetAddress ();
                 // Customer's host name
                String hostname = ia.getHostName ();
                // Customer's IP
                String ip = ia.getHostAddress ();
                System.out.println ("Client's host name:" + hostname + "ip address:" + ip);
                
             }
        
            
        } catch (IOException e) {
            e.printStackTrace ();
        }

    }

}
Server thread class

package socket.object;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/ **
 * Server thread class
 *
 * /
public class ServerThread extends Thread {

    Socket socket = null;

    public ServerThread (Socket socket) {

        this.socket = socket;
    }

    
    @Override
    public void run () {
        
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {
            // Get input and output streams
             ois = new ObjectInputStream (socket.getInputStream ());
             oos = new ObjectOutputStream (socket.getOutputStream ());
            
            // Get user information
            User user = (User) ois.readObject ();
            System.out.println ("Here is the server: the user information is:");
            System.out.println ("User name:" + user.getName () + "Password:" + user.getPassowrd () + "Gender:" + user.getSex () + "email:" + user.getEmail () );
            // Sound on the client
            String info = "Information has been received, welcome to";
            oos.writeObject (info);
            
            // Close the stream
            oos.close ();
            ois.close ();
            socket.close ();
        
        } catch (IOException e) {
            e.printStackTrace ();
        } catch (ClassNotFoundException e) {
            e.printStackTrace ();
        }

        
        
    }

}
 

Six, UDP (datagram)
 

 
 

Client

package udpsocket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/ **
 * Client
 * /
public class AskClient {

    public static void main (String [] args) {
        // Declare data packet and socket objects
        DatagramPacket dp = null;
        DatagramSocket ds = null;
        //server address
        InetAddress ia = null;
        // Server port
        int port;
        try {
            // 1. Determine the information sent to the server, server address, port
            String mess = "I want to ask a question";
            byte [] buf = mess.getBytes ();
            // Send address
             ia = InetAddress.getByName ("localhost");
            // Port of the server
             port = 9100;
            // 2. Create a data packet and send the specified length of information to the specified address port
             dp = new DatagramPacket (buf, buf.length, ia, port);
            // 3. Create a datagram socket object
            ds = new DatagramSocket ();
            // 4. Send data
            ds.send (dp);
            
            // Receive server data
             dp = new DatagramPacket (buf, buf.length);
            ds.receive (dp);
            String replys = new String (buf, 0, dp.getLength ());
            System.out.println ("Service response:" + replys);
            
            // 5. Release resources
            ds.close ();
        } catch (UnknownHostException e) {
            e.printStackTrace ();
        } catch (SocketException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
        
        
        
        
        
    }

}
 

service end

package udpsocket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketException;

/ **
 * Service-Terminal
 * /
public class AskServer {

    public static void main (String [] args) {
        
        try {
            // 1. Create a receiver (server) socket and bind the port number
            DatagramSocket ds = new DatagramSocket (9100);
            // 2. Determine the array size of the data packet received
            byte [] buf = new byte [1024];
            // 3. Create a data packet of the receiving type and store the data in an array
            DatagramPacket dp = new DatagramPacket (buf, buf.length);
            // 4. Receive data via socket
            ds.receive (dp);
            // 5. Parse the data sent by the sender
            String mess = new String (buf, 0, dp.getLength ());
            // Output customer IP and words
            System.out.println (dp.getAddress (). GetHostAddress () + "Customer says:" + mess);
            // Respond to the client
            String reply = "What's wrong";
            byte [] replys = reply.getBytes ();
            // The address of the client's IP address
            SocketAddress sa = dp.getSocketAddress ();
            DatagramPacket dpsend = new DatagramPacket (replys, replys.length, sa);
            //send
            ds.send (dpsend);
            
            // 6. Release resources
            ds.close ();
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace ();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace ();
        }
        

    }

}

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.