Computer questions (Elementary)-How to Implement Socket communication between the client and the server through Java)
Many beginners are not familiar with java Network Communication and are not familiar with related concepts. Here we mainly implement socket communication, which is widely used in java, for example, QQ and MSN are both based on socket communication. What is socket? A socket is an ip + port. Let's take a look at how the simplest socket communication is implemented through an instance.
First, implement the server code:
Package com. socket. demo; import java. io. bufferedReader; import java. io. inputStream; import java. io. inputStreamReader; import java.net. serverSocket; import java.net. socket; public class Server {public static void main (String [] args) {try {ServerSocket serverSocket = new ServerSocket (8888); System. out. println ("---------------- Server Run, start listening for requests --------------"); Socket socket = serverSocket. accept (); // starts listening to InputStream InputStream = socket. getInputStream (); BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (inputStream); // obtain the request content String info; while (info = bufferedReader. readLine ())! = Null) {System. out. println ("I Am a server, client request:" + info);} // close the resource socket. shutdownInput (); bufferedReader. close (); inputStream. close (); socket. close (); serverSocket. close () ;}catch (Exception exception ){}}}
Then implement the client code:
Package com. socket. demo; import java. io. IOException; import java. io. outputStream; import java. io. printWriter; import java.net. socket; import java.net. unknownHostException; public class Client {public static void main (String [] args) {try {// send to port 8888 Socket socket = new Socket ("127.0.0.1", 8888 ); // output stream OutputStream outputStream = socket. getOutputStream (); PrintWriter printWriter = new PrintWriter (outputStream); prin TWriter. write ("Hello on the server, I'm a client. "); PrintWriter. flush (); // close the resource printWriter. close (); outputStream. close (); socket. close ();} catch (UnknownHostException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}
The client sends the information to the server. After receiving the information, the server outputs the information on the console. Well, the simplest socket communication is implemented.