1. Use the socket for communication:
1, the service side:
1 PackageCom.neo.demo;2 3 Importjava.io.IOException;4 ImportJava.io.PrintStream;5 ImportJava.net.ServerSocket;6 ImportJava.net.Socket;7 8 Public classServer {9 Ten Public Static voidMain (string[] args)throwsioexception{ One A //Create a ServerSocket to listen for connection requests to the socket -ServerSocket ServerSocket =NewServerSocket (30000); - //to receive requests from clients in a circular manner the while(true) - { - //each time a socket client request is received, the server side also generates a corresponding socket -Socket s =serversocket.accept (); + //wraps the output stream corresponding to the socket into a printstream -PrintStream PS =NewPrintStream (S.getoutputstream ()); + //perform normal IO operations APs.println ("Hello, you have received a New year greeting from the server!" "); at //turn off the output stream and close the socket - ps.close (); - s.close (); - } - } -}
2. Client:
1 PackageCom.neo.demo;2 3 ImportJava.io.BufferedReader;4 Importjava.io.IOException;5 ImportJava.io.InputStreamReader;6 ImportJava.net.Socket;7 8 Public classClient {9 Ten Public Static voidMain (string[] args)throwsioexception{ One ASocket socket =NewSocket ("127.0.0.1", 30000); - //wrapping the socket input stream into BufferedReader -BufferedReader br =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); the //for IO operations -String line =br.readline (); -SYSTEM.OUT.PRINTLN ("Data from server:" +Line ); - //close the input stream, socket + br.close (); - socket.close (); + A } at}
Run the server class first, you will see that the server has been waiting, because the server used a dead loop to receive requests from the client, and then run the client class, you will see the program output: "Data from the server: Hello, you received the server's New Year blessing!" ", which indicates that the client and server-side communication succeeded!
Deep Web request Process