WebService is an encapsulation of the socket, making remote invocation easier, so how troublesome is it to use a socket? Take a look.
To do a simple weather query:
Service side:
Public class socketserver { Public Static void Main(string[] args) {DataInputStream DataInputStream =NULL; DataOutputStream DataOutputStream =NULL;Try{//Start Socket serverServerSocket ServerSocket =NewServerSocket (8888);/** * Plus while (true) to keep the server running and responsible for the server to stop running when a client connection is successful. */ while(true) {//Listen for client connections, the Accept () method is a blocking method, and if there is no client connection, subsequent code will not executeSocket socket = serversocket.accept (); DataInputStream =NewDataInputStream (Socket.getinputstream ()); DataOutputStream =NewDataOutputStream (Socket.getoutputstream ());//Get the name of the city that the client came fromString CityName = Datainputstream.readutf (); System.out.println ("from client ..."+ CityName);//query weather and return query resultsString result ="Sunny Day"; Dataoutputstream.writeutf (result); } }Catch(IOException e) {E.printstacktrace (); }finally{Try{if(dataoutputstream!=NULL) Dataoutputstream.close (); }Catch(IOException e) {E.printstacktrace (); }Try{if(datainputstream!=NULL) Datainputstream.close (); }Catch(IOException e) {E.printstacktrace (); } } }}
Client:
Public classsocketclient { Public Static void Main(string[] args) {Socket socket =NULL; DataOutputStream DataOutputStream =NULL; DataInputStream DataInputStream =NULL;Try{//Create socket ConnectionSocket =NewSocket ("127.0.01",8888);//Get output streamDataOutputStream =NewDataOutputStream (Socket.getoutputstream ());//Send dataDataoutputstream.writeutf ("Haikou");//Receive DataDataInputStream =NewDataInputStream (Socket.getinputstream ());//Get input streamString result = Datainputstream.readutf (); System. out. println (Result); }Catch(IOException e) {E.printstacktrace (); }finally{Try{if(socket!=NULL) Socket.close (); }Catch(IOException e) {E.printstacktrace (); }Try{if(datainputstream!=NULL) Datainputstream.close (); }Catch(IOException e) {E.printstacktrace (); }Try{if(dataoutputstream!=NULL) Dataoutputstream.close (); }Catch(IOException e) {E.printstacktrace (); } } }}
Using a socket is a stream of data, to prevent coding problems, to open the stream, to close the stream, and if you use WebService, you do not have to think about it at all.
Using a socket to simulate a simple webservice call