After reading Socket network programming, I feel this is amazing.
Below is the sending end of the socket:
/* Socket programming, sending end
1. Set up the port for sending the socket, and use mongoramsocket
2. encapsulate the data, add the acceptor address and port number, and add datagrampacket.
3. Send data packet send ()
4. Disable Resources
*/Import java. Io. *; import java.net .*;
Public class socketsend {
Public static void main (string [] ARGs) throws exception {
// Create the sender ramsocket datagramsocket = new datagramsocket ();
Bufferedreader = new bufferedreader (New inputstreamreader (system. In ));
// Create data, encapsulate and package the data, and add the acceptor address and port number string STR = NULL;
While (STR = bufferedreader. Readline ())! = NULL ){
// Datagrampacket (byte [] Buf, int length, inetaddress address, int port)
Byte [] Buf = Str. getbytes ();
// 192.168.1.0 is the network address, that is, the network segment number.
// If a message is sent from the broadcast address 255 in the LAN, all IP addresses in the segment can receive the message.
Required rampacket restart reampacket = new datagrampacket (BUF, Buf. length, inetaddress. getbyname ("192.168.0.101"), 20000 );
// Send
Datagramsocket. Send (datagreampacket );
If ("over". Equals (STR) {break ;}}
// Close the resource
Datagramsocket. Close ();
}}
The following is the acceptor:
// Socket acceptor /*
1. Create the acceptor port, datagramsocket, and specify the port number.
2. Create a data packet to store the received data packet. New datagrampacket (BUF, Buf. length), receive (datagrampacket)
3. extract data from data packets
4. Close the resource.
*/
Import java.net .*;
Public class socketreceive {
Public static void main (string [] ARGs) throws exception {
// Create a port number
Datagramsocket = new datagramsocket (20000 );
// Datagrampacket (byte [] Buf, int length)
// Create a data packet to store the received data packet
Byte [] Buf = new byte [1, 1024];
While (true ){
Datagrampacket = new datagrampacket (BUF, Buf. Length );
Datagramsocket. Receive (datagrampacket );
// Obtain the data in the data packet
String IP = datagrampacket. getaddress (). gethostaddress ();
String data = new string (datagrampacket. getdata (), 0, datagrampacket. getlength ());
Int Port = datagrampacket. getport ();
System. Out. println (IP + "..." + Data + "..." + port );
If ("over". Equals (data) {break ;}}
// Close the resource
Datagramsocket. Close ();
}}