Establish two-way communication via java.net package

Source: Internet
Author: User
Tags socket

Leverage the network capabilities provided by the java.net package. In the case of connected flow communication, the server-side operation is generally:

⑴ creates a ServerSocket object that listens for requests from clients on the specified port.

⑵ the Accept () method returns a socket object when the request is received.

⑶ creates an input and output stream object with the above socket object.

⑷ interacts with customers through input and output streams.

⑸ Interactive, close the input, output stream and socket.

The ⑹ service program ends and closes the serversocket.

Implementing code code classes such as:

try{
boolean flag=true;
Socket clientSocket=null;
ServerSocket serverSocket = new ServerSocket(0);
System.out.println("Server listen on: " +serverSocket.getLocalPort());
while(flag){
clientSocket=serverSocket.accept();
DataInputStream is=new DataInputStream( new bufferedInputStream(client
Socket.getInputStream()));
PrintStream os=new PrintStream( new bufferedOutputStream(clientSocket.
getOutputStream()));
// 处理Applet请求
os.close();
is.close();
clientSocket.close();
}
serverSocket.close();
}catch( IOException e){
System.err.println(" Exception: "+e);
}

The actions on the client are:

⑴ create a socket object to establish a connection to the server.

⑵ creates an input and output stream with the socket object.

⑶ interacts with the server.

⑷ Interactive, close the input, output stream and socket.

Implement code classes such as:

try {
Socket clientSocket =new Socket("serverName",7);
OutputStream os=clientSocket.getOutputStream();
DataInputStream is=new DataInputStream( clientSocket.getInputStream())
;
// 其它操作.
os.close();
is.close();
clientSocket.close();
}catch(Exception e){
System.err.println("Exception:"+e);
}

This approach relies only on standard Java network support and does not require additional software packages or tools, so it is fairly concise and flexible, making it easy to meet certain special needs.

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.