1, the Client
package com.ljb.app.socket;import java.io.BufferedReader;import java.io.IOException; Import java.io.inputstream;import java.io.inputstreamreader;import java.io.outputstream;import java.io.printwriter;import java.net.socket;import java.net.unknownhostexception;/** * Client (simulate customer login and receive server response information) * @author LJB * @version 2015 March 11 */public class LoginClient { /** * @param args */ public static void main (String[] args) { try { // Establish a client Socket connection, specify the location of the server and port socket socket = new socket ("localhost", 8800); // get socket read/write Flow OutputStream os = Socket.getoutputstream (); printwriter pw = new printwriter (OS); // receivedTake input stream inputstream is = socket.getinputstream (); bufferedreader br = new bufferedreader (New inputstreamreader (IS)); // write String info = "user name: Tom, Password: 123456"; Pw.write (info); pw.flush (); socket.shutdownoutput (); // Receive server Response String reply = null; while ( ! ((Reply = br.readline ()) == null)) { system.out.println ("I am the client, the server response is:" + reply); } // Close Flow br.close (); is.close (); pw.close (); os.close (); socket.close (); } catch (unknownhostexception e) { e.printstacktrace (); } catch (ioexception e) { e.printstacktrace (); } }}
2, server-side
package com.ljb.app.socket;import java.io.BufferedReader;import java.io.IOException; Import java.io.inputstream;import java.io.inputstreamreader;import java.io.outputstream;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;/** * Server (receive client login information and respond) * @author LJB * @version 2015 March 11 */public class LoginServer { /** * @param args */ public static void main (String[] args) { try { // Set up a server binding specified port socket (serversocket) and start listening ServerSocket serverSocket = new ServerSocket (8800); // use the Accept () method to block waiting for monitoring, to obtain a new connection Socket socket = serversocket.accept (); // get input stream inputstream is = Socket.getinputstream (); bufferedreader br = new bufferedreader (new inputstreamreader (IS)); // get the output stream outputstream os = socket.getoutputstream (); printwriter pw = new PrintWriter (OS); // read user input information string info = null; while (!) ( (Info = br.readline ()) == null)) { system.out.println ("I am a server, User information: " + info); } // response Information String reply = "Welcome"; pw.write (reply); pw.flush (); // Close Flow pw.close (); os.close (); br.close (); is.close (); socket.close (); serversocket.close (); } catch (ioexception e) { E.printstacktrace (); } }}
Operation Result:
Client:
I am the client, the server response is: Welcome
Service side:
I am the server, the user information is: User name: Tom, Password: 123456
Analog Client Login (TCP-based socket programming)