Many beginners for the Java network communication is not very familiar with the relevant concepts are not very clear, here we mainly implement socket communication, socket communication in Java application is very wide, such as QQ and MSN are based on the socket communication, what is the socket? Simply understand that the socket is the ip+ port. Use an example to see how the simplest socket communication is implemented.
First implement server-side 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 ("Run----------------server, start monitoring requests----------------"); Socket socket=serversocket.accept ();//Start monitoring InputStream inputstream=socket.getinputstream (); BufferedReader bufferedreader=new BufferedReader (New InputStreamReader (InputStream));//Get Request Content string Info;while (( Info=bufferedreader.readline ())!=null) {System.out.println ("I am the server side, client request is:" +info);} Close 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 8888 port socket socket=new socket ("127.0.0.1", 8888);//output Stream OutputStream outputstream=socket.getoutputstream (); PrintWriter printwriter=new PrintWriter (outputstream);p rintwriter.write ("Server side Hello, I am the client. ");p Rintwriter.flush ();//Close Resource printwriter.close (); Outputstream.close (); Socket.close ();} catch (Unknownhostexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}}}
Structure
Then we first run the server side: (The order cannot be reversed OH)
Then start the client:
As you can see here, the client sends the information to the server side, and the server receives the information and outputs the information in the console. Well, the simplest of a socket communication is implemented.
Please pay attention to my favorite friends.
On-Machine topic (beginner)-Java network operation-socket implements client and server-side communication (Java)