Introduction to socket programming and JAVA Implementation

Source: Internet
Author: User
Java is a language that can be used for network programming. It provides two powerful network support mechanisms: URL-based access to network resources and socket-based communication, to meet different requirements. First, the URL is used to access Internet resources. Second, it is used for client/server (Client/Server) Mode Applications and applications that implement certain special protocols, the communication process is implemented based on the transport layer interface socket in the TCP/IP protocol. This article briefly introduces the JAVA Implementation Method of socket programming.

Most communication components used between servers are implemented based on socket interfaces. Socket is the network communication endpoint for two-way data transmission between two programs. It is identified by an address and a port number. Each service program must be on a port when providing the service, and the client that wants to use the service must also connect to the port. Because the socket is based on the transport layer, it is a relatively primitive communication protocol mechanism. The data in the socket is represented by byte stream information. Therefore, to complete a specific application, both parties must format and interpret the data as agreed by both parties, we can see that using socket programming is troublesome, but it is more flexible and more widely used.

Some may ask, what is the working mode of the client/server? Well, I 'd like to introduce their working modes with a picture below.

So how does a Java application implement the above process? The java.net package contains two types of socket and serversocket, which are used to create socket communication on the client and server respectively.

Let's take a look at the process of writing a client segment program:

1. First, call the socket class constructor to create a socket stream with the specified IP address of the server or the specified host name and the specified port number as the parameter, the socket stream creation process includes the process of requesting the server to establish a communication connection.

2. After the Client Communication socket is established. You can use the socket method getinputstream () and getoutputstream () to create an input/output stream. In this way, after the socket class is used, the network input and output are also converted to the process of using stream objects.

3. Use the corresponding method of the input and output stream object to read and write throttling data, because the socket used for communication Linglong is an endpoint that establishes a connection with the server, therefore, data is obtained or sent to the server by connecting to the server. In this case, we can process byte stream data based on the protocol between the client and the server to complete the communication tasks between the two parties.

4. After the communication task is completed, we use the close () method of the stream object to close the input and output streams for network communication, and use the close () method of the socket object to close the socket.

Next, I would like to use a simple example to further introduce the compiling of the client program.

Code 1:

Import java. Io .*;

Import java.net .*;

Public class socketcommunicationclient

{

Public static void main (string [] ARGs)

{

Try {

Socket clientsocket = new socket ("mice", 9000); // create a stream socket and connect it to port 9000 on the host mice

Outputstream output = clientsocket. getoutputstream (); // write an output stream of bytes to this socket

Datainputstream input = new datainputstream (clientsocket. getinputstream ());

File: // create a new data input stream to read data from the specified input stream

Int C;

String response;

While (C = system. In. Read ())! =-1) // receives input strings from the screen and splits them into characters

{

Output. Write (byte) C );

If (C = '/N') // if the character is carriage return, the output string is buffered.

{

Output. Flush ();

Response = input. Readline ();

System. Out. println ("Communication:" + response );

}

}

Output. Close ();

Input. Close ();

Clientsocket. Close ();

} Catch (exception e ){

System. Err. println ("exception:" + E );

}

}

}

This program is a very simple example of data communication. The program first creates a socket and connects it to port 9000 on the host mice, and then opens the input/output stream, then, the program receives characters from the standard input and writes them into the stream. Every full row (marked by the user's press Enter) sends the strings in the buffer zone to the server-side program on mice for processing, wait for the server to respond. The input. Readline () method call will cause the program to stop until the response message is received, and the program will repeat the process until the user enters the abort character. Finally, the program will close the socket input/output stream and close the connection between the socket and the server.


The above shows how to use Java to compile the socket interface program of the client. Below I also want to briefly talk about the Java implementation method of the socket interface program on the server side. The process is as follows:

1. First, call the serversocket class to create a serversocket object with a port number as the parameter, that is, the socket that the server-side service program listens to on the specified port.

2. The server program uses the serversocket object's accept () method to receive connection requests from the client program. At this time, the server will remain stuck until it receives a connection request from the client, this method returns a new socket class instance, representing the communication endpoint of the communication link established with the client in the service program. If you use Java multi-threaded programming, You can implement concurrent servers and continue to listen for connection requests from other customers.

3. Use the new socket object to create the input and output stream objects.

4. Use the stream object method to complete client data transmission, identify and process request data from the client according to the agreed protocol, and return the processing result to the client.

5. After the client completes work, the server program closes the stream and socket for communication with the client.

6. Close the socket used for listening between the end of the server program.

Let's take a look at the JAVA Implementation of a server-side program:

Code 2:

Import java.net .*;

Import java. Io .*;

Public class socketcommunicationserver

{

Public static void main (string [] ARGs)

Try

{

Boolean flag = true; // set the flag to true.

Socket Client = NULL; // create a socket client to receive requests from the client

String inputline;

Serversocket = new serversocket (9000); // create a server socket with port 9000

System. Out. println ("the server listens on port 9000 ");

File: // you can also use serversocket. getlocalport () to obtain the port number.

While (FLAG)

{

Client = serversocket. Accept ();

File: // listen and accept the connection to this socket. This method will be blocked until a connection is generated.

Datainputstream input = new datainputstream (New bufferedinputstream (client. getinputstream ()));

Printstream output = new printstream (New bufferedoutputstream (client. getoutputstream ());

While (inputline = input. Readline ())! = NULL)

{

If (inputline. Equals ("stop "))

{

Flag = false;

Break;

}

Output. println (inputline );

Output. Flush ();

}

Output. Close ();

Input. Close ();

Client. Close ();

}

Serversocket. Close ();

} Catch (ioexception e ){}

}

}

}

Above, I briefly talked about the socket programming mechanism and the implementation method of socket programming using Java, hoping to help you.

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.