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.