One, server-side
1. Create a ServerSocket, the server-side socket, bind the specified port, and listen for this port
ServerSocket Server = new ServerSocket (8888);
2. Call the Accept () method, start listening, wait for the client to connect, before the connection succeeds, in a blocked state, the returned socket, used to connect with the client
Socket socket = server.accept ();
3. Get the input stream to read the information sent by the client
InputStream is = Socket.getinputstream ();//Byte input stream
InputStreamReader ISR = new InputStreamReader (IS);//Character input stream
BufferedReader br = new BufferedReader (ISR);//Buffered input stream
String info = null;
while ((Info=br.readline ()) = null) {
Looping through data
SYSTEM.OUT.PRINTLN ("Client said:" +info);
}
Socket.shutdowninput ();//Close input stream
4, get the output stream, the user responds to the client's request
OutputStream OS = Socket.getoutputstream ();//byte output stream
PrintWriter pw = new PrintWriter (OS);//Print output stream
Pw.write ("Server side has accepted your request, allow login");
Pw.flush ();
Socket.shutdownoutput ();//Close output stream
5. Close Resources
Br.close ();
Isr.close ();
Is.close ();
Pw.close ();
Os.close ();
Socket.close ();
Server.close ();
Second, the client
1. Create a client socket, specify the server address and port number to connect to
Socket socket = new Socket ("127.0.0.1", 8888);
2, get the output stream, send information to the server side
OutputStream OS = Socket.getoutputstream ();//byte stream
PrintWriter pw = new PrintWriter (OS);//Print Flow
Pw.write ("username: admin; password: 123");
Pw.flush ();
Socket.shutdownoutput ();//Close output stream
3. Get the input stream to read the information sent from the server side
InputStream is = Socket.getinputstream ();//Byte input stream
InputStreamReader ISR = new InputStreamReader (IS);//Character input stream
BufferedReader br = new BufferedReader (ISR);//Buffered input stream
String info = null;
while ((Info=br.readline ()) = null) {
SYSTEM.OUT.PRINTLN ("service side said:" +info);
}
Socket.shutdowninput ();//Close input stream
4. Close Resources
Br.close ();
Isr.close ();
Is.close ();
Pw.close ();
Os.close ();
Socket.close ();
Socket communication based on TCP protocol