Java Network Programming

Source: Internet
Author: User

Java provides a rich API for network programming in the Java.net package, which mainly includes:

URLConnection, HttpURLConnection is used to obtain data from the server side;

ServerSocket and Scoket establish TCP servers and clients;

Datagramsocket set up UDP server and client;

    • ServerSocket and Scoket establish a TCP/IP connection

First, we need to establish a listening client TCP connection request through ServerSocket. When the client's request is heard, the server assigns a socket to communicate with the client.

Creating a client for sending and receiving data becomes fairly straightforward:

New Socket ("localhost", 8080);         New true );        Out.println ("test");         New BufferedReader (new  InputStreamReader (                socket.getinputstream ()));          //  must output line feed, otherwise no data will be output to customer          socket.close ();

The server side is also fairly simple:

ServerSocket ServerSocket =NewServerSocket (8080); Socket Clientsocket=serversocket.accept (); PrintWriter out=NewPrintWriter (Clientsocket.getoutputstream (),true); BufferedReader in=NewBufferedReader (NewInputStreamReader (Clientsocket.getinputstream ()));        String Line;  while(line = In.readline ())! =NULL) {out.println ("From Server:" + line);//the line feed must be output, otherwise no data will be output to the customer} clientsocket.close (); Serversocket.close ();

    • Datagramsocket establishing a UDP connection

Unlike TCP connections, UDP does not have a strictly server-side and client-only point. Both parties can send data to each other, the receiving party does not necessarily receive the data, the sender does not know whether the data is received. The data sent is not necessarily received in the original order. Obviously, there is no need to establish a connection beforehand, so there is a lot of unnecessary overhead. This is useful for applications that do not care about small amounts of data loss, such as live streaming.

 Public classUdptest { Public Static voidMain (string[] args)throwsIOException, interruptedexception {NewThread (NewRunnable () {@Override Public voidrun () {Try{receive ();//must start a new thread}Catch(IOException e) {e.printstacktrace ();                }}). Start ();    Send (); }     Public Static voidSend ()throwsIOException {datagramsocket datagramsocket=NewDatagramsocket (); byte[] buffer = "Test UDP". GetBytes (); InetAddress receiveraddress=Inetaddress.getlocalhost (); Datagrampacket Packet=Newdatagrampacket (buffer, buffer.length, receiveraddress,8800); Datagramsocket.send (packet); //Not blockDatagramsocket.close (); }     Public Static voidReceive ()throwsIOException {datagramsocket datagramsocket=NewDatagramsocket (8800); byte[] buffer =New byte[10]; Datagrampacket Packet=Newdatagrampacket (buffer, buffer.length); Datagramsocket.receive (packet); //it would block until data receivedSystem.out.println (NewString (Packet.getdata ()));    Datagramsocket.close (); }}

    • HttpURLConnection communication with the server

GET

    

New URL ("http://163.com");         = url.openconnection ();         Try New BufferedReader (new  InputStreamReader (                conn.getinputstream ()));) {            null;              while (null ! = (line = reader.readline ())) {                System.out.println (line);            }        }

POST

Conn.setdooutput (true//  post        new//                  Writer.close ();

Here's a jarurlconnection class for getting information about jar packages:

// jar:<url>! /{entry}        String urlstring = "jar:http://butterfly.jenkov.com/"                + "container/download/"                + " jenkov-butterfly-container-2.9.9-beta.jar!/";         New URL (urlstring);         = (jarurlconnection) jarurl.openconnection ();         = Connection.getmanifest ();

Java Network Programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.