Java Socket Communication

Source: Internet
Author: User

Socket communication refers to the communication between two programs of two computers, each of which is called a socket, but is divided into clients and servers.

Java.net provides the serversocket and socket classes, respectively, for the server and client.

Communication process:

To establish a socket connection, the client program requests a connection, the server program listens on all the ports, determines if there is a client server request, when the client requests a port connection, the server binds the other's IP and port number to form a socket, so that the server and the client set up a private virtual connection, Can communicate with each other, after the end of the communication to remove the virtual connection.

Programming Steps: The server establishes a server socket ServerSocket, and specifies the port number to listen for client requests, and then establishes a socket to communicate with the client, and the client establishes a socket at the same port to communicate with the server.

Java.net contains the above two classes:

Main Method Description:

ServerSocket (int port) creates a server socket object on the specified port

ServerSocket (int port,int count) count is the maximum number of connections

Sorket (inetaddress ip,int port) using the specified IP and port to establish the socket object

Sorket (String host,int port) using the specified host and port to establish the socket object

The above two methods have three options for Boolean stream (Boolean indicates whether streaming communication is selected)

You can use the getInputStream and getoutstream of the socket class to read and write data input and output streams. But to do exception handling, read the input and output stream to establish a more easy-to-operate inputstreamreader and out ... Close (Socket) disconnects after communication ends.

Socket application:

Java Socket Communication

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.