/** * Defines an endpoint to receive data and print the socket service on the console * to establish a service-side via Seversocket () and listening to a port * Obtain the connected client object through the Accept method this method is blocked * The client sends the data server to use the The client object to be applied and read the data using the Read stream * * class Tcpserverdemo {public static void main (string[] args) throws IOException {System
. OUT.PRINTLN ("Server start ...");
Establish a service-side socket service and listen for a port serversocket ss = new ServerSocket (10005);
Gets the client object Socket s = ss.accept (); Connection Status System.out.println ("Connected:" + s.getinetaddress (). Gethostaddress (). toString () + "PORT:" + s.getport ())
;
while (true) {System.out.println ("Waiting to receive Message:");
Read Data InputStream in = S.getinputstream ();
byte[] data = new byte[1024];
int len = in.read (data);
String str = new string (data, 0, Len);
if ("886". Equals (str)) {System.out.println ("Bye");
Ss.close ();
S.close ();
System.exit (0);
} System.out.println (str);
SYSTEM.OUT.PRINTLN ("Send a Message:");
BufferedReader ins = new BufferedReader (new InputStreamReader (system.in));
In order to send the data to obtain the output stream in the socket outputstream out = S.getoutputstream ();
Out.write (Ins.readline (). GetBytes ()); }
}
}
/** * Send a text data to the server */class Tcpclientdemo {public static void main (string[) args) throws I
oexception {///Create socket service specify destination host and port socket s = new socket ("127.0.0.1", 10005);
while (true) {System.out.println ("Send info:");
BufferedReader ins = new BufferedReader (new InputStreamReader (system.in));
String str = ins.readline ();
In order to send the data to obtain the output stream in the socket outputstream out = S.getoutputstream ();
Out.write (Str.getbytes ());
if ("886". Equals (str)) {System.out.println ("Bye");
S.close ();
System.exit (0);
//Get Data System.out.println ("Wait for reply:");
InputStream in = S.getinputstream ();
byte[] data = new byte[1024];
int len = in.read (data);
System.out.println (new String (data, 0, Len)); }
}
}