Server
Package Com.witwicky.socket.basicsocket;import Java.io.ioexception;import Java.io.inputstream;import Java.io.outputstream;import Java.net.serversocket;import Java.net.socket;public class Server {public static void main ( String[] (args) {int port = 43523; ServerSocket serversocket = null; try {System.out.println ("===\nstart recive message ..."); ServerSocket = new ServerSocket (port); Socket socket = serversocket.accept (); InputStream InputStream = Socket.getinputstream (); StringBuffer sb = new StringBuffer (); byte[] bytes = new byte[1024]; int Len; while (len = inputstream.read (bytes))! =-1) {System.out.println ("Length:" + len); Sb.append (New String (bytes, 0, Len, "UTF-8")); } System.out.println (Sb.tostring ()); System.out.println ("End recive message......\n==="); String returncontent = "recive oveR. "; OutputStream outputstream = Socket.getoutputstream (); Outputstream.write (Returncontent.getbytes ("UTF-8")); Outputstream.close (); Inputstream.close (); Socket.close (); Serversocket.close (); } catch (IOException e) {e.printstacktrace (); } }}
Connected to the target VM, address: ' 127.0.0.1:61818 ', Transport: ' Socket ' ===start recive message......length:180 because the C programme Language is very famous for using it as the first demo program, so later programmers continue this habit when they learn to program or perform device debugging. End Recive message......===disconnected from the target VM, address: ' 127.0.0.1:61818 ', Transport: ' Socket ' Process finish Ed with exit code 0
Client
Package Com.witwicky.socket.basicsocket;import Java.io.ioexception;import Java.io.inputstream;import Java.io.outputstream;import Java.net.socket;public class Client {public static void main (string[] args) {Strin G host = "127.0.0.1"; int port = 43523; try {System.out.println ("= = ="); Socket socket = new socket (host, port); OutputStream outputstream = Socket.getoutputstream (); String content = "because it was used as the first demo program in the C programme Language, it was so famous that later programmers continued the habit when they learned to program or debug the device." "; Outputstream.write (Content.getbytes ()); Socket.shutdownoutput (); int Len; byte[] bytes = new byte[1024]; InputStream InputStream = Socket.getinputstream (); StringBuffer sb = new StringBuffer (); while (len = inputstream.read (bytes))! =-1) {Sb.append (New String (bytes, 0, Len, "UTF-8")); } System.out.println ("Service return Content:" + SB. toString ()); System.out.println ("= = ="); Inputstream.close (); Outputstream.close (); Socket.close (); } catch (IOException e) {e.printstacktrace (); } }}
Connected to the target VM, address: ' 127.0.0.1:61828 ', Transport: ' Socket ' ===service return content:recive Over.===disco Nnected from the target VM, address: ' 127.0.0.1:61828 ', Transport: ' Sockets ' Process finished with exit code 0
Java Socket Server Client