First, let's look at the simplest socket client and server instance:
Client
Public classmyclient { Public Static voidMain (string[] args) {ObjectOutputStream Oos=NULL; Bytearrayoutputstream Bos=NULL; Socket Client=NULL; Try{people P=NewPeople ("2", "Yangyu", "4", "5", "6"); Oos=NewObjectOutputStream (BOS =NewBytearrayoutputstream ()); Initializes an object output stream of Oos.writeobject (p); Writes a People object to the output streambyte[] bytes =Bos.tobytearray (); Gets the byte array of the People object (that is, the serialized people) client=NewSocket ("127.0.0.1", 20007); Connect the 127.0.0.1 20007 Port Client.setsotimeout (10000); Set timeout time Client.getoutputstream (). write (bytes); Send byte[] array to serverbyte[] bytes1 = ioutils.readfully (Client.getinputstream (), 18,false); Gets the server return data System.out.println (NewString (bytes1)); System.out.println (bytes1.length); } Catch(Exception e) {e.printstacktrace (); }finally { Try{oos.close (); Bos.close (); System.out.println (client.isclosed ()); Client.close (); } Catch(IOException e) {e.printstacktrace (); } } }}
Server
Public classMyServer { Public Static voidMain (string[] args) {ServerSocket server=NULL; Socket Client=NULL; ObjectInputStream Ois=NULL; Bytearrayinputstream bis=NULL; Try{Server=NewServerSocket (20007); Start the socket server and listen on the 20007 port client=server.accept ();//block and wait for the receiving client to send the data and generate the clientbyte[] bytes = ioutils.readfully (Client.getinputstream (),-1,false)//Get the data that the client sends over the BIS=Newbytearrayinputstream (bytes); Ois=NewObjectInputStream (bis); People people=(People) ois.readobject ();//deserialization System.out.println ("People name:" +people.getname ()); String Res= "message has been received"; Client.getoutputstream (). Write (Res.getbytes ());//Send data to the client}Catch(Exception e) {e.printstacktrace (); }finally { Try{bis.close (); Ois.close (); Client.close (); Server.close (); } Catch(IOException e) {e.printstacktrace (); } } }}
The above one client and one server, the simplest example, but embodies the socket programming.
If you need the server service to listen to the port all the time, then only the loop is needed (Server.accept () will block the wait request), as for high concurrency response, then the server handles the data service to the thread pool.
Java--socket Programming