Some simple TCP and UDP applications

Source: Internet
Author: User

 


The most important part in network programming is SOCKET, which is actually the principle of listening port. The principle behind sending text messages via mobile phones should be roughly the same (I understand it in this way), and the best thing in JAVA is "No pain in connecting networks ".
The most basic spirit of the network is to connect two machines. The "called party" is the server, and the "looking for someone" is called the client, therefore, in connection, servers and clients are a relative concept. However, we identify machines mainly through IP addresses and ports.
"Transmission Control Protocol" TCP and "User Datagram Protocol" are two different protocols. JAVA basically supports these two protocols in the same way, the biggest difference between them is the reliability and speed of sending. The former is a reliable protocol compared with the latter, and the latter is certainly much faster. Below we will use two sockets for Demonstration:

Eg1:

// Clients. java

Import java. io .*;
Import java.net .*;

Public class Clients
{
Public static void main (String [] args) throws Exception
{
InetAddress addr = InetAddress. getByName (null );
Socket socket = new Socket (addr, 2000 );
PrintWriter out =
New PrintWriter (
New BufferedWriter (
New OutputStreamWriter (
Socket. getOutputStream (), true );
Byte [] B = new byte [2048];
String msg = new String (B, 0, System. in. read (B ));
Out. println (msg );
Socket. close ();
}
}

// Servers. java

Import java. io .*;
Import java.net .*;

Public class Servers
{
Public static void main (String [] args) throws Exception
{
ServerSocket s = new ServerSocket (2000 );
Try {
While (true ){
Socket socket = s. accept ();
Try {
BufferedReader in =
New BufferedReader (
New InputStreamReader (
Socket. getInputStream ()));
StringBuffer sb = new StringBuffer ();
Int c;
While (c = in. read ())! =-1 ){
Char ch = (char) c;
Sb. append (ch );
}
System. out. println (sb. toString ());

} Catch (IOException e ){
Socket. close ();
} Finally {
Socket. close ();
}
} // While
} Finally {
S. close ();
} // Try
} // Main
}

This program mainly uses Servers for unlimited listening, while Clients is a client sending program, and all their ports use 2000.

Eg2:

// UDPsend. java
Import java. io .*;
Import java.net .*;

/**
* This class sends the specified text or file as a datax to
* Specified port of the specified host.
**/
Public class UDPSend {
Public static final String usage =
"Usage: java UDPSend..." +
"Or: java UDPSend-f ";

Public static void main (String args []) {
Try {
// Check the number of arguments
If (args. length <3)
Throw new IllegalArgumentException ("Wrong number of args ");

// Parse the arguments
String host = args [0];
Int port = Integer. parseInt (args [1]);

// Figure out the message to send.
// If the third argument is-f, then send the contents of the file
// Specified as the fourth argument. Otherwise, concatenate
// Third and all remaining arguments and send that.
Byte [] message;
If (args [2]. equals ("-f ")){
File f = new File (args [3]);
Int len = (int) f. length (); // figure out how big the file is
Message = new byte [len]; // create a buffer big enough
FileInputStream in = new FileInputStream (f );
Int bytes_read = 0, n;
Do {// loop until weve read it all
N = in. read (message, bytes_read, len-bytes_read );
Bytes_read + = n;
} While (bytes_read <len) & (n! =-1 ));
}
Else {// Otherwise, just combine all the remaining arguments.
String msg = args [2];
For (int I = 3; I <args. length; I ++) msg + = "" + args [I];
Message = msg. getBytes ();
}

// Get the internet address of the specified host
InetAddress address = InetAddress. getByName (host );

// Initialize a datatipacket with data and address
DatagramPacket packet = new DatagramPacket (message, message. length,
Address, port );

// Create a datatesocket, send the packet through it, close it.
DatagramSocket dsocket = new DatagramSocket ();
Dsocket. send (packet );
Dsocket. close ();
}
Catch (Exception e ){
System. err. println (e );
System. err. println (usage );
}
}
}

// UDPreceive. java
Import java. io .*;
Import java.net .*;

/**
* This program waits to receive extends rams sent the specified port.
* When it Comes To es one, it displays the sending host and prints
* Contents of the datax as a string. Then it loops and waits again.
**/
Public class UDPReceive {
Public static final String usage = "Usage: java UDPReceive ";
Public static void main (String args []) {
Try {
If (args. length! = 1)
Throw new IllegalArgumentException ("Wrong number of args ");

// Get the port from the command line
Int port = Integer. parseInt (args [0]);

// Create a socket to listen on the port.
DatagramSocket dsocket = new DatagramSocket (port );

// Create a buffer to read into rams into. If anyone sends us
// Packet containing more than will fit into this buffer,
// Excess will simply be discarded!
Byte [] buffer = new byte [2048];

// Create a packet to receive data into the buffer
DatagramPacket packet = new DatagramPacket (buffer, buffer. length );

// Now loop forever, waiting to receive packets and printing them.
For (;;){
// Wait to receive a datasync
Dsocket. receive (packet );

// Convert the contents to a string, and display them
String msg = new String (buffer, 0, packet. getLength ());
System. out. println (packet. getAddress (). getHostName () +
":" + Msg );

// Reset the length of the packet before reusing it.
// Prior to Java 1.1, wed just create a new packet each time.
Packet. setLength (buffer. length );
}
}
Catch (Exception e ){
System. err. println (e );
System. err. println

Related Article

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.