This class implements a client socket (which can also be called a "socket"). A socket is a communication endpoint between two machines.
New Socket (Ip,port); // creates a stream socket and connects it to the specified port number for the specified IP address.
The following is a complete sample of the client:
Socketclientdemo.java
Public classSocketclientdemo {/*** Send request data to the specified address *@paramipaddr *@paramReqdata*/ Public voidsendreq (String ipaddr,string reqdata) {Socket client=NULL; BufferedReader BR=NULL; Bufferedoutputstream Bos=NULL; String Respstr= ""; //set the character set encoding formatString charactercoding = "GBK"; //splitting a string of type Ip:port intDotpos = Ipaddr.indexof (":"); String IP= ipaddr.substring (0, Dotpos). Trim (); intPort = Integer.parseint (ipaddr.substring (dotpos+1). Trim ()); Try{Client=NewSocket (Ip,port); //Set Send wait time (in s)Client.setsolinger (true, 5); //setting the time-out (unit: MS)Client.setsotimeout (5000); //get the output stream from the client sideBOS =NewBufferedoutputstream (Client.getoutputstream ()); Bos.write (Reqdata.getbytes (charactercoding)); Bos.flush (); BR=NewBufferedReader (NewInputStreamReader (Client.getinputstream ())); Respstr=Br.readline (); System.out.println ("Respstr is:>>>>>>" +respstr); } Catch(unknownhostexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } finally { if(BR! =NULL) { Try{br.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } if(bos!=NULL) { Try{bos.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } if(client!=NULL) { Try{client.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } } }}View Code
Test Class Code:
Socketclienttest.java
Public class socketclienttest { /** @param args * / Public Static void Main (string[] args) { // TODO auto-generated method stub New Socketclientdemo (); Client.sendreq ("192.168.1.136:9997", "This is socket client!" ); }}
View Code
Java Socket Network Programming client's solution