Unlike the client program, the server side uses ServerSocket, which is the following constructor
ServerSocket Server = new ServerSocket (80);
The code above indicates that the server is listening on port 80.
Based on the client code of the previous article, put the server-side code
Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;
public class talkserver{/** server port, listening port * * private static final int server_port = 4700;
public static void Main (String args[]) {try {ServerSocket server=null;
try{server=new ServerSocket (server_port);
catch (Exception e) {System.out.println ("Can not listen to:" +e);
Socket Socket=null;
try{//Use Accept () blocking waits for customer request socket=server.accept (); catch (Exception e) {System.out.println ("Error.")
+E);
} String Line; The input stream is obtained from the socket object and the corresponding BufferedReader object is constructed BufferedReader is=new BufferedReader (New InputStreamReader (
Socket.getinputstream ()));
The output stream is obtained from the socket object, and the PrintWriter object PrintWriter os=new printwriter (Socket.getoutputstream ()) is constructed.
The BufferedReader object is constructed by the keyboard (system default input device) device BufferedReader sin=new BufferedReader (New InputStreamReader (system.in)); Print on the monitor (standard output) from the clientRead-in String System.out.println ("Client:" +is.readline ());
Reads a string line=sin.readline () from the standard input;
while (!line.equalsignorecase ("Bye")) {//output the string to the client os.println (line);
Refreshes the output stream so that the client immediately receives the string Os.flush ();
System.out.println ("Server:" +line);
System.out.println ("Client:" +is.readline ());
Line=sin.readline (); } os.close (); Close socket output stream is.close (); Close the socket input stream socket.close (); Close socket Server.close ();
Close ServerSocket} catch (Exception e) {e.printstacktrace (); }
}
}