Java Network Programming--socket

Source: Internet
Author: User

The network is the medium that connects the different computer, the different computer relies on the network to communicate with each other, namely transmits the data.

Java is related to network programming is the socket (socket), which as an abstract structure, the implementation of communication-related methods, constitute a complete set of communication mechanisms.

Of course, the socket itself is independent of the programming language concept, like the data structure and algorithm, it is not part of Java, but a recognized communication solution, most of the language has implemented the socket-related communication functions.

Principle

The socket provides a mechanism for communication between two computers by using TCP (Transmission Control Protocol). The specific way is: The server will first create the ServerSocket object, and it is listening to a local port state, and the client by creating a socket to connect to the corresponding port on the server, so the connection is established, The Accept method of the ServerSocket on the server will return a socket object, and now both machines can communicate through the standard write and read methods of the socket object.

The complete steps are as follows:

    • The server instantiates a ServerSocket object that communicates through the port on the server.
    • The server calls the Accept () method of the ServerSocket class, and the method waits until the client connects to the given port on the server.
    • When the server is waiting, a client instantiates a Socket object, specifying the server name and port number to request a connection.
    • The constructor of the Socket class attempts to connect the client to the specified server and port number. If the communication is established, a Socket object is created on the client to communicate with the server.
    • On the server side, the Accept () method returns a new socket reference to the server that is connected to the client's socket.
Java Implementation Service-side--serversocket

The server first instantiates a ServerSocket class object that calls the Accept () method to listen on a local port and then goes into a blocking state until the client's socket connection request arrives.

Methods of the ServerSocket class:

Method
public serversocket (int port) throws IOException
public ServerSocket (int port, int backlog) throws IOException
public ServerSocket (int port, int backlog, inetaddress address) throws IOException
Public ServerSocket () throws IOException

The most common use is the first construction method, which is to create a new serversocket and to listen directly to one of the local ports.

There are also some common methods for ServerSocket classes:

Method Description
public int Getlocalport () Returns the port on which this socket listens.
Public Socket Accept () throws IOException Listens for and accepts connections to this socket.
public void setsotimeout (int timeout) Enables/disables so_timeout, in milliseconds, by specifying a time-out value.
public void bind (socketaddress host, int backlog) Bind the ServerSocket to a specific address (IP address and port number).
Client

The client directly instantiates the socket class and attempts to connect to the corresponding port on the server.

First look at the method of constructing the socket class.

Method Description
Public Socket (String host, int port) throws Unknownhostexception, IOException. Creates a stream socket and connects it to the specified port number on the specified host.
Public Socket (inetaddress host, int port) throws IOException Creates a stream socket and connects it to the specified port number for the specified IP address.
The public Socket (String host, int port, inetaddress localaddress, int localport) throws IOException. Creates a socket and connects it to the specified remote port on the specified remote host.
Public sockets (inetaddress host, int port, inetaddress localaddress, int localport) throws IOException. Creates a socket and connects it to the specified remote port on the specified remote address.
Public Socket () Create an SocketImpl socket from the system default type

When the socket is constructed, it will automatically attempt to connect to the specified server and port first.

Connection creation

After the connection is established, both sides of the socket can begin to communicate freely, the communication process, both sides of the socket object is the same nature (the server ServerSocket call Accept () method has returned the socket object, So the server is now also a socket object for communication.

Here are some ways that the socket object can be called during communication:

Method Description
public void Connect (socketaddress host, int timeout) throws IOException Connect this socket to the server and specify a timeout value.
Public inetaddress getinetaddress () Returns the address of the socket connection.
public int Getport () Returns the remote port that this socket is connected to.
public int Getlocalport () Returns the local port to which this socket is bound.
Public socketaddress getremotesocketaddress () Returns the address of the endpoint for this socket connection, or null if not connected.
Public InputStream getInputStream () throws IOException Returns the input stream for this socket.
Public OutputStream Getoutputstream () throws IOException Returns the output stream for this socket.
public void Close () throws IOException Close the socket.
Instance

Server class:

/** *  */package socket;import java.io.PrintStream;import java.net.ServerSocket;import java.net.Socket;/** * @author Tom Qian * @email [email protected] * @github https://github.com/bluemapleman * @date 2017年8月18日 */ public class Server{    private static int port=10000;     private static String ip="127.0.0.1";        /**     * @param args     */    public static void main(String[] args) throws Exception    {        ServerSocket ss=new ServerSocket(10000);        while(true){            Socket s=ss.accept();            PrintStream ps=new PrintStream(s.getOutputStream());            ps.print("您好,您收到了服务器的新年祝福!");                        ps.close();            s.close();        }    }}

Client class:

/** * @author Tom Qian * @email [email protected] * @github https://github.com/bluemapleman * @date 2017年8月18日 */package socket;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.Socket;public class Client{    /**     * @param args     */    public static void main(String[] args) throws Exception    {        int port=10000;        Socket socket=new Socket("127.0.0.1",port);        BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));        String line=br.readLine();        System.out.println("来自服务器的数据:"+line);        br.close();        socket.close();    }}

Start the server class first, then start the client class (otherwise the client side will report Connectexception, reject the connection error!). Of course! Service side there is not even a receiver, how can you send the letter of the past? ), the effect is as follows:

This article refers to:
[1] Rookie tutorial--java Network programming

Java Network Programming--socket

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.