Java programming-sun Xin Java is no difficulty lesson12 Network Programming
Highlights of this section:
1. Network Programming
2. TCP-based socket programming
3. UDP-based socket programming
4. url and Uri
Details:
1. For more information about computer networks, See Xie xiiren's computer network.
2. TCP-based socket programming
Shows the TCP-based communication model between the socket program client and the server:
Server programming:
① Call serversocket (INT port) to create a server socket and bind it to the specified port;
② Call accept () to listen for connection requests. If the client requests connection, the connection is accepted and the communication socket is returned.
③ Call the getoutputstream () and getinputstream of the socket class to obtain the output stream and input stream and start sending and receiving network data.
④ Close the communication socket.
Client programming:
① Call socket () to create a stream socket and connect it to the server;
② Call the getoutputstream () and getinputstream of the socket class to obtain the output stream and input stream and start sending and receiving network data.
③ Close the communication socket.
The simple TCP test code is as follows:
Import Java. io. inputstream; import Java. io. outputstream; import java.net. inetaddress; import java.net. serversocket; import java.net. socket; public class TCP {// server side public static void server () {try {serversocket Ss = new serversocket (6000); socket SA = ss. accept (); inputstream is = sa. getinputstream (); outputstream OS = sa. getoutputstream (); OS. write ("Hello welcome you! ". Getbytes (); byte [] Buf = new byte [100]; int Len = is. read (BUF); system. out. write (BUF, 0, Len); SS. close (); SA. close (); is. close (); OS. close ();} catch (exception e) {e. printstacktrace () ;}// client public static void client () {try {Socket Client = new socket (inetaddress. getbyname (null), 6000); // The port number must be the same as that on the server. inputstream is = client. getinputstream (); byte [] Buf = new byte [100]; int Len = is. read (BUF); system. out. write (BUF, 0, Len); outputstream OS = client. getoutputstream (); OS. write ("Hi, this is zhangsan ". getbytes ();} catch (exception e) {// todo auto-generated catch blocke. printstacktrace () ;}} public static void main (string [] ARGs) {If (ARGs. length> 0) {server () ;}else {client ();}}}
Shows the running effect:
The code for a TCP test program compiled using multiple threads is as follows:
Import Java. io. bufferedoutputstream; import Java. io. inputstream; import Java. io. outputstream; import java.net. inetaddress; import java.net. serversocket; import java.net. socket; public class threadtcp extends thread {private socket s; threadtcp (socket s) {This. S = s;} public void run () {try {inputstream is = S. getinputstream (); outputstream OS = S. getoutputstream (); bufferedoutputstream Bos = new bufferedoutputstrea M (OS); // OS. Write ("Hello welcome you! ". Getbytes (); Bos. Write (" Hello welcome you! ". Getbytes (); // refresh the BOS buffer. flush (); byte [] Buf = new byte [100]; int Len = is. read (BUF); system. out. println (new string (BUF, 0, Len); S. close (); is. close (); OS. close ();} catch (exception e) {// todo auto-generated catch blocke. printstacktrace () ;}} public static void server () {try {serversocket Ss = new serversocket (6000); While (true) {socket SA = ss. accept (); New threadtcp (SA ). start ();} // ss. close ();} catch (exception e) {e. printstacktrace () ;}} public static void client () {try {Socket Client = new socket (inetaddress. getbyname (null), 6000); // The port number must be the same as that on the server. inputstream is = client. getinputstream (); byte [] Buf = new byte [100]; int Len = is. read (BUF); system. out. write (BUF, 0, Len); outputstream OS = client. getoutputstream (); OS. write ("Hi, this is wangwu ". getbytes ();} catch (exception e) {// todo auto-generated catch blocke. printstacktrace () ;}} public static void main (string [] ARGs) {If (ARGs. length> 0) {server () ;}else {client ();}}}
Shows the running effect:
3. UDP-based socket programming
Shows the UDP-based communication model between the socket client and the server:
Write the receiver program:
① Call mongoramsocket (INT port) to create a datagram socket and bind it to the specified port;
② Call mongorampacket (byte [] Buf, int length) to create a byte array to receive UDP packets.
③ Call receive () of the datagramsocket class to receive UDP packets.
④ Close the datagram socket.
Write the sender program:
① Call datagramsocket () to create a datagram socket;
② Call mongorampacket (byte [] Buf, int offset, int length, inetaddress address, int port) to create the UDP packet to be sent.
③ Call the send () method of the datagramsocket class to send a UDP packet.
④ Close the datagram socket.
The simple UDP test code is as follows:
Import java.net. datagrampacket; import java.net. datagramsocket; import java.net. inetaddress; public class UDP {// sending end public static void send () {try {datagramsocket DS = new datagramsocket (); byte [] Buf = "Hello, this is zhangsan ". getbytes (); datagrampacket dp = new datagrampacket (BUF, Buf. length, inetaddress. get byname ("localhost"), 8000); DS. send (DP); // accept Data byte [] bufrecv = new byte [100]; datagrampacket DPR = new data Grampacket (bufrecv, 100); DS. receive (DPR); int Len = DPR. getlength (); system. out. write (bufrecv, 0, Len); DS. close ();} catch (exception e) {e. printstacktrace () ;}/// the acceptor public static void Recv () {try {// receives data using datagramsocket DS = new datagramsocket (8000 ); // create the mongoramsocketbyte [] Buf = new byte [100]; mongorampacket dp = new mongorampacket (BUF, 100); DS. receive (DP); int Len = DP. getlength (); system. out. println (New stri Ng (BUF, 0, Len); // send data string STR = "welcome you! "; Datagrampacket DPS = new datagrampacket (Str. getbytes (), str. length (), DP. getaddress (), DP. getport (); DS. send (DPS); DS. close ();} catch (exception e) {// todo auto-generated catch blocke. printstacktrace () ;}} public static void main (string [] ARGs) {If (ARGs. length> 0) {Recv () ;}else {send ();}}}
Shows the running effect:
4. url and Uri
URL (Uniform Resource Locator), a common resource locator. Http://www.mybole.com.cn/index.asp?a url=.
Uri (Uniform Resource Identifier), a common resource identifier.
A URI is purely a symbolic structure used to specify different parts of a string that constitutes a web resource. A URL is a special type of URI that contains sufficient information for searching a resource. Other Uris, such as mailto: myoble@mybole.com.cn, do not belong to the locator, because it does not have any data to look for based on this identifier. This type of URI is called urn (common resource name ).
In the Java library, the URI class does not contain any method used to access the settings of the Universal Resource Identifier. Its only function is to perform analysis.
On the contrary, the URL class can open a string that reaches the resource.
The download test code is as follows:
Import javax. swing. *; import Java. AWT. event. windowadapter; import Java. AWT. event. using wevent; import Java. AWT. event. actionlistener; import Java. AWT. event. actionevent; import Java. AWT. button; import Java. AWT. headlessexception; import Java. AWT. textfield; import Java. io. bufferedreader; import Java. io. fileoutputstream; import Java. io. inputstream; import Java. io. inputstreamreader; import java.net. inetaddress; import Java.net. URL; import java.net. urlconnection; import java.net. unknownhostexception; import javax. swing. jprogressbar; public class download {@ suppresswarnings ("deprecation") public static void main (string [] ARGs) throws headlessexception, unknownhostexception {jframe JF = new jframe ("Download "); JF. setsize (600,400); JF. setlocation (100,100); // create related controls jpanel P = new jpanel (); jlabel JL = new jlabel ("Please input u RL: ", jlabel. left); Final textfield TF = new textfield ("", 30); button BTN = new button ("Download"); p. add (JL, 0); p. add (TF, 1); p. add (BTN, 2); JF. getcontentpane (). add (P, "North"); Final jtextarea TA = new jtextarea (); JF. getcontentpane (). add (TA, "center"); // response close button JF. addwindowlistener (New windowadapter () {public void windowclosing (invalid wevent arg0) {// todo auto-generated method stubsystem. exit (0) ;}}); // response to the Download button BTN. addactionli Stener (New actionlistener () {public void actionreceivmed (actionevent e) {try {string STR = TF. gettext (); system. out. println (STR); Url url = new URL (STR); urlconnection urlc = URL. openconnection (); // display URL specified page information string line = system. getproperty ("line. separator "); TA. append ("Host:" + URL. gethost (); TA. append (line); TA. append ("port:" + URL. getdefaultport (); TA. append (line); TA. append ("contendtype:" + urlc. getcont Enttype (); TA. append (line); TA. append ("contendlength:" + urlc. getcontentlength (); int Len = urlc. getcontentlength (); // get the input/output stream inputstream is = urlc. getinputstream (); inputstreamreader ISR = new inputstreamreader (is); bufferedreader BR = new bufferedreader (ISR); fileoutputstream Fos = new fileoutputstream ("1.html "); /* // read and store string strline by row; while (strline = BR. readline ())! = NULL) {FOS. write (strline. getbytes (); FOS. write (line. getbytes ();} * // read and store int data by byte stream; while (Data = BR. read ())! =-1) {FOS. write (data) ;}br. close (); FOS. close ();} catch (exception ex) {ex. printstacktrace () ;}}); JF. show ();}}
Shows the running effect:
This download program is not complete yet and needs to be improved.