Java --- Socket programming UDP/TCP

Source: Internet
Author: User

• Socket facilitates applications to access the communication protocol TCP/IP.
• Socket is the end point of the communication link. We can think of socket as a telephone. With Socket, we have a communication tool. We can think of the IP address as the phone number and the port number as the extension number.
 
1. TCP-based socket programming.
• Java.net. ServerSocket is used to create a socket on the server.
• Java.net. Socket is used to create the socket Socket of the client.
• InetAddress (java.net. InetAddress) Class: Used to indicate IP addresses.


• TCP-based sockets can be called Stream sockets.
• The server is equivalent to a listener for listening to ports.
• Communication Between the server and the client is implemented by an input/output stream.
 
The server code is as follows:
[Java]
Import java.net .*;
Import java. io .*;

Class SocketTCPServer extends Thread // Let the class inherit as the Thread class
{
Private Socket s;
SocketTCPServer (Socket s)
{
This. s = s;
}

Public static void main (String [] args)
{
Server ();
}

Public void run () // This is the thread method.
{
Try
{// Of course, if you do not want to directly send data, a stream with buffer will be created.
OutputStream OS = s. getOutputStream ();
BufferedOutputStream bos = new BufferedOutputStream (OS );
// OS. write ("my name is xuneng! ". GetBytes ());
Bos. write ("my name is xuneng! ". GetBytes ());

InputStream is = s. getInputStream ();
Byte [] buf = new byte [100]; // do not forget to add new
Int len = is. read (buf );
System. out. println (new String (buf, 0, len ));

Bos. close ();
Is. close ();
OS. close ();
S. close ();
}
Catch (Exception e)
{
E. printStackTrace ();
}

}

Public static void server () // After completion, remember to close various sockets
{
Try
{
ServerSocket ss = new ServerSocket (8000); // a custom Port
While (true) // the server will always start like this.
{
System. out. println ("the server is starting .......");
Socket s = ss. accept (); // always waiting to receive messages
New SocketTCPServer (s). start (); // when the request is received, a socket is returned and a thread is created.
}
}
Catch (Exception e)
{
E. printStackTrace ();
}

}

}

The client code is as follows:
[Java]
Import java.net .*;
Import java. io .*;

Class SocketTCPClient
{
Private Socket s;
SocketTCPClient (Socket s)
{
This. s = s;
}

Public static void main (String [] args)
{
Client ();
}

Public static void client ()
{
Try
{
Socket s = new Socket (InetAddress. getByName ("localhost"), 8000); // The port number must be consistent.

OutputStream OS = s. getOutputStream ();
OS. write ("Hello World! ". GetBytes ());

InputStream is = s. getInputStream ();
Byte [] buf = new byte [1, 100];
Int len = is. read (buf );
System. out. println (new String (buf, 0, len ));

OS. close ();
Is. close ();
S. close ();

}
Catch (Exception e)
{
E. printStackTrace ();
}
}
}

2. UDP-based socket programming.
The creation process is as follows:
• Java.net. DatagramSocket (Data telegraph socket ).
• Java.net. DatagramPacket (a data telegraph package containing sent information ).


• UDP-based sockets are datagram sockets.
• Both data packets must be constructed first.
• The intgetLength () function in the DatagramPacket packet returns the actual number of accepted bytes, and byte [] getData () returns the received data.
• To receive information from the sender, you must know the InetAddress getAddress () address of the sender and the port number int getPort () bound to the sender process ().
• After the datagram socket is successfully sent, a virtual connection is established, and both parties can send data.
 
The sending code is as follows:
[Java]
Import java.net .*;
Import java. io .*;
/*
* Sending end, equivalent to the client.
*/
Class SocketUDPSend
{
Public static void main (String [] args)
{
Sed ();
}

Public static void sed ()
{
Try
{
DatagramSocket ds = new DatagramSocket ();
String str = "haha, my name is xuneng! ";
DatagramPacket dp = new DatagramPacket (str. getBytes (), 0, str. length (),
InetAddress. getByName ("localhost"), 8600); // address sent to the local machine, port 8600
Ds. send (dp );

// Demonstrate accepting the returned data.
Byte [] buf = new byte [1, 100];
Required rampacket dp2 = new DatagramPacket (buf, 100); // byte array, Length
Ds. receive (dp2 );
System. out. println (new String (buf, 0, dp2.getLength ()));
Ds. close ();
}
Catch (Exception e)
{
E. printStackTrace ();
}
}

}

The receiving code is as follows:
[Java]
Import java.net .*;
Import java. io .*;
/*
* The receiver, that is, the server. Listening for ports all the time.
*/
Class SocketUDPRecv
{
Public static void main (String [] args)
{
Recv ();
}

Public static void recv ()
{
Try
{
DatagramSocket ds = new DatagramSocket (8600 );
Byte [] buf = new byte [1, 100];
DatagramPacket dp = new DatagramPacket (buf, 100 );
Ds. receive (dp );
System. out. println (new String (buf, 0, dp. getLength ()));

// Demonstrate how to return data to the sender, which must be accepted by the sender
String str = "Yes, I have Ed! ";
DatagramPacket dp1 = new DatagramPacket (str. getBytes (), str. length (),
Dp. getAddress (), dp. getPort ());
Ds. send (dp1 );

Ds. close ();
}
Catch (Exception e)
{
E. printStackTrace ();
}
}
}

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.