Javase Getting Started learning 48:socket network communication Programming (II.)

Source: Internet
Author: User

Three socket communication (1) Socket

Socket sockets are the basis of network communication, which can be considered as IP address + port, which is used to distinguish the communication between different applications.

Two Java applications can exchange data through a two-way network communication connection, a section of this bidirectional link is called a socket. Socket

Typically used to implement client-server connections.

The two class sockets and ServerSocket defined in the java.net package are used to implement two-way connections between the client and server.

(2) Socket communication model


Socket communication:


Socket Communication Implementation steps:

1) Create ServerSocket and sockets.

2) Open the input/output stream connected to the socket.

3) Read/write the socket according to the protocol.

4) Close the input/output stream and close the socket.

(3) ServerSocket class

The ServerSocket class implements a server socket. The server socket waits for the request to pass through the network. It performs certain actions based on the request, and can then

can return a result to the requestor.

How to construct the ServerSocket class:

methods of the ServerSocket class:



(4) Socket class

The socket class implements a client socket (which can also be called a "socket"). Sockets are the end of communication between two machines.

How to construct the Socket class:


Method of Socket class:




four TCP programming via sockets (1) TCP

The TCP protocol is connection-oriented, reliable, ordered, and sends data in a byte-stream manner.

A class that implements network communication based on the TCP protocol:

1) Socket class for Client

2) server-side Soservercket class

(2) TCP-based socket communication specific steps:

Server-side:

1) Create the ServerSocket object and bind the listening port.

2) Listen for client requests through the accept () method.

3) After the connection is established, read the request information sent by the client through the input stream.

4) sends a response message through the output flow to the client.

5) Close related resources.

Client:

1) Create a socket object that indicates the address and port number of the server you want to connect to.

2) After the connection is established, send the request information through the output to the server side.

3) Gets the message of the server response through the input stream.

(3) Example

Single-to-one (server and one client) TCP programming Instance code:

Server.java Source file Code:

<span style= "FONT-SIZE:18PX;" >import java.net.*;import java.io.*;/** Socket communication based on TCP protocol, implementation of user login * Server-side */public class Server{public static void Main ( String[] (args) {TRY{//1 creates a server-side socket, which is serversocket, specifies the bound port, and listens on the port serversocket serversocket = new ServerSocket (8111); 2 Call the Accept () method to start listening, waiting for the client's connection System.out.println ("* * * server is about to start, waiting for client connections * * *"); Socket socket = serversocket.accept ();//3 gets the input stream and reads the client information//byte input stream InputStream is = Socket.getinputstream ();/ Convert byte input stream to character input stream InputStreamReader ISR = new InputStreamReader (IS, "utf-8");//Add buffer for character input stream BufferedReader br = new BufferedReader (ISR);//Read Data string info = null;//Loop reads the client's information while ((Info=br.readline ())!=null) {System.out.println (" I am the server, the client says: "+info);} Closes the input stream socket.shutdowninput ();//4 gets the output stream, responds to client requests OutputStream Os=socket.getoutputstream ();//wrapper for print flow PrintWriter pw= New PrintWriter (OS);p w.write ("Welcome! ");//Refresh Cache Pw.flush ();//5 Close Resource Pw.close (); Os.close (); Br.close (); Isr.close (); Is.close (); Socket.close (); Serversocket.close ();} catch (IOException e) {e.printstacktrace ();}}} </span> 

Client.java Source file Code:

<span style= "FONT-SIZE:18PX;" >import java.net.*;import java.io.*;/** Socket communication based on TCP protocol, implement user login * client */public class Client{public static void Main ( String[] (args) {TRY{//1 Create client socket, specify server address and port        socket socket = new socket ("localhost", 8111),//2 get output stream, send message to server// The byte output stream outputstream OS = Socket.getoutputstream ();//wraps the output stream as a print stream printwriter pw = new PrintWriter (OS);p W.write ("username: admin; Password: 123 ");p W.flush ();//Close output stream socket.shutdownoutput ();//Get input stream and read server-side response information InputStream is=socket.getinputstream (); BufferedReader br=new BufferedReader (New InputStreamReader (IS)); String info=null;//loops through the server-side information while ((Info=br.readline ())!=null) {System.out.println ("I am the client, server-side said:" +info);} 4 Close resource br.close (); Is.close ();p w.close (); Os.close (); Socket.close ();} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}}} </span>

Operation Result:

Server-side results:


Client results:


Javase Getting Started learning 48:socket network communication Programming (II.)

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.