Java Network Programming

Source: Internet
Author: User

A network programming

Logical Port : The identity of the different processes used to identify the logical address of the process

Valid ports : 0~65535 where 0~ system uses or retains ports

//inetaddress IP objects in JavaImportjava.net.*;classIpdemo { Public Static voidMain (string[] args)throwsunknownhostexception {//get an IP object by name (IP string or hostname)inetaddress IP = inetaddress.getbyname ("www.baidu.com");//java.net.UnknownHostExceptionSystem.out.println ("Addr:" +ip.gethostaddress ()); System.out.println ("Name:" +ip.gethostname ()); }}

Two sockets

endpoint for socket communication

is to provide a mechanism for network services to communicate at both ends of the socket network communication is actually the socket between the communication data between two sockets through IO Transmission ( as long as the network transmission must have a Socket)

1. UDP

Encapsulate data and sources and purposes in a packet that does not need to establish a connection

The size of each datagram is within the limit of 64k

Because no connection is an unreliable protocol

No need to establish a fast connection speed

//set up a UDP socket service Datagramsocket (the socket object that encapsulates the UDP transport protocol has the send and receive functions)//package The data that will be sent into a packet//send packets out via the socket service of UDP Dategrampacket//Close Socket//in the case of UDP transmission, it needs to be clear that one is the sending side and the receiver//The sending and receiving ends are two separate running programs//the sending side of UDPImportjava.net.*;classUdpsend { Public Static voidMain (string[] args)throwsException {//1 Setting up a UDP socket serviceDatagramsocket ds =NewDatagramsocket (8888);//specifies that the send port does not specify that the system is randomly assigned. //2 Specify the specific data to be sentString Text = "UDP snapped"; byte[] buf =text.getbytes (); //3 encapsulating data as a packetDatagrampacket DP =NewDatagrampacket (buf, Buf.length,inetaddress.getbyname ("10.1.31.127"), 10000); //4 Send data packets with the Send method of the socket serviceDs.send (DP); //5 Closing ResourcesDs.close (); }}//The receiving end of the UDPclassudprece { Public Static voidMain (string[] args)throwsException {//1 The socket service that creates UDP must be clear that the function of a port is that only the data sent to this port is the data that the receiver can process.Datagramsocket ds =NewDatagramsocket (10000); //2 defining a packet for storing received data first defines a byte array packet that stores the data in a byte array        byte[] buf =New byte[1024]; Datagrampacket DP=NewDatagrampacket (buf, buf.length); //3 The received data is stored in a packet via the socket service's Receive methodDs.receive (DP);//This method is a blocking method//4 Get the specific data contents of the packet, such as IP, port, data, etc. by means of the packetString IP =dp.getaddress (). gethostaddress (); intPort =Dp.getport (); String text=NewString (Dp.getdata (), 0, Dp.getlength ());//converts a valid part of a byte array into a stringSYSTEM.OUT.PRINTLN (IP + ":" + Port + "--" +text); //5 Closing ResourcesDs.close (); }}

2. TCP

Establish a connection to form a channel for transmitting data

Make large data transfers in a connection

Complete connection via three handshake is a reliable protocol

Must establish connection efficiency is slightly lower

//Establish client (Socket) and server-side (ServerSocket)//data transfer via IO stream in the socket after connection is established//Close Socket//client and server side are two separate applications//TCP ClientImportjava.net.*;ImportJava.io.*;//demand client sends a data to server side//1 establishing a TCP socket service requires a specific address and port (so you can try to establish a connection if the connection fails with an exception)---> Three-time handshake//2 If the connection succeeds, it means that the channel has created a socket stream that has been generated as long as the read stream and the write stream in the socket stream can be obtained as long as the two stream objects are obtained through getInputStream and Getoutputstream//3 Closing ResourcesclassTcpClient { Public Static voidMain (string[] args)throwsException {Socket s=NewSocket ("10.1.31.69", 10002); OutputStream out= S.getoutputstream ();//gets the output stream object in the socket streamOut.write ("TCP pops up". GetBytes ());    S.close (); }}//TCP Service SideclassTCPServer { Public Static voidMain (string[] args)throwsException {//1 Creating a service-side socket service and listening on a portServerSocket SS =NewServerSocket (10002); //2 server in order to provide services to clients gets the contents of the client can be obtained through the Accept method of the connected client objectSocket s = ss.accept ();//Get Client ObjectString IP =s.getinetaddress (). gethostaddress (); SYSTEM.OUT.PRINTLN (IP+ "..... connected"); //3 You can communicate with a specific client by getting the socket in the socket objectInputStream in = S.getinputstream ();//read the client's data using the client object's socket read stream        byte[] buf =New byte[1024]; intLen =In.read (BUF); String text=NewString (buf, 0, Len);        System.out.println (text); //4 If the communication ends close the resource (to shut down the client and then close the server)S.close ();    Ss.close (); }}

The most likely problem with TCP transmission

Client connections on Both sides of the server are waiting for no data transfer because the read method or The ReadLine method is blocking

Workaround : Use the shutdowninput shutdownoutput method to customize the end tag

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.