1, the so-called socket is also commonly referred to as "socket", used to describe the IP address and port, is a handle of a communication chain. Applications typically make requests to the network through sockets or answer network requests.
The top three ways to operate a Java socket are:
Accept (): Mainly for the server side to generate "blocking", waiting for the client's link request, and return a client socket instance;
getInputStream (): The method is mainly used to obtain the network connection input, while returning a InputStream object instance;
Getoutputstream (): The method is the opposite of the getinputstream above.
2, generally to establish a Java socket connection, should first clear the server side and the client, the server side using ServerSocket listening to the specified port, using accept waiting for client requests, link links, start the session, complete the session, close the link. (Note that the general closure of the socket should be server-side, said later); The client uses the socket to make a link request to a port on a server in the network, the connection is successful, the session is started, the session is completed, and the socket is closed.
2. Sample code:
Server-side:
Package com.icer.server; Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.printwriter;import Java.net.serversocket;import Java.net.Socket; /** * Server * * @author icer * */public class Server {private ServerSocket SS; Private Socket S; Private BufferedReader BR; Private PrintWriter PW; Public Server () {try {ss = new ServerSocket (10000); System.out.println ("Server is starting ..."); s = ss.accept (); br = new BufferedReader (New InputStreamReader (S.getinputstream ())); PW = new PrintWriter (S.getoutputstream (), true); String line = Br.readline (); System.out.println (line); Pw.println ("Your word is:" + line); Pw.println ("HelloWorld"); Br.close (); Pw.close (); } catch (IOException IE) {ie.printsTacktrace (); }} public static void Main (string[] args) throws Exception {new Server (); }}
Client:
Package com.icer.client; Import Java.io.bufferedreader;import java.io.file;import Java.io.fileinputstream;import Java.io.IOException;import Java.io.inputstreamreader;import Java.io.printwriter;import Java.net.Socket; /** * Client * @author icer * */public class Client {private Socket s; Private BufferedReader BR; Private BufferedReader Line; Private PrintWriter PW; Private String line = ""; Public Client () {try{s = new Socket ("127.0.0.1", 10000); PW = new PrintWriter (S.getoutputstream (), true); br = new BufferedReader (New InputStreamReader (S.getinputstream ())); Pw.println ("Hello"); line = Br.readline (); System.out.println (line); Br.close (); Pw.close (); }catch (IOException IE) {ie.printstacktrace (); }} public static void Main (string[] args) throws Exception {new Client (); }}
Java Socket Programming Example code explanation