Create a Java project in Eclipse Testmyserversocket
package com.yeqc.testmyserversocket.main;import java.io.ioexception;import java.net.serversocket;import java.net.socket;import Javax.swing.joptionpane;public class myserversocket {public static void main ( String[] args) {//1-65535try {serversocket serversocket = new serversocket ( 54321)//serversocket.accept ();//Call Accept () to listen for the client's connection/** *accept () is a blocking method, so here it blocks the current thread * Since it blocks the current main thread, it is created here because it is only a demonstration * this is not strictly true and will be written in the right way in the future * * In the current serversocket is already listening to this port of 12345 on this machine * when this port its accept () is called, that is to say there is a client connected to this port */Socket socket = serversocket.accept ();//Establish a connection/** * once the Accept () is executed and the socket is assigned, this means that the client is already connected */ Joptionpane.showmessagedialog (null, "has client connected to the 12345 port of this machine");//Popup Prompt box} catch (ioexception e) {e.printstacktrace ();}}}
At this point you can see that the current program is running and not stopped, and there is no output prompt box, so you can see that the current program is blocked in the statement: Serversocket.accept ();
Then open the browser, enter 127.0.0.1:54321 in the Address bar (127.0.0.1 to read the address of the computer, after the colon is the port to read), you can see the pop-up prompt box.
Socket communication in Java (ii) establishment and use of ServerSocket