TCP and UDP talk about some simple applications (1)
Network programming is the most important SOCKET, which is also the principle that monitor port. And we use a mobile phone text message exactly the same principle should be broadly (I understand this is), JAVA and the most outstanding point is "no pain networking."
The basic spirit of the network is to link up the two machines, "the party calls" the server is, "looking to the side" is called the client, so that the connecting server, the client is a relative concept the. We logo on the machines primarily through the IP address and port to the distinction.
"Transmission Control Protocol" TCP and the "User Datagram Protocol" are two different agreements, JAVA the support of these two basic agreement is the same, and their own biggest difference is sent reliability and speed, with the former than the latter is a reliable agreement, which is of course a much faster pace, we were below the demonstration with two SOCKET:
Eg1:
/ / Clients.java
Import java.io. *;
Import java.net .*;
Public class Clients
(
Public static void main (String [] args) throws Exception
(
InetAddress.getByName InetAddress addr = (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 used to carry out unlimited Servers monitor, and the client is sent Clients program, they all use the port in 2000.
Eg2:
/ / UDPsend.java
Import java.io. *;
Import java.net .*;
/ **
* This class sends the specified text or file as a datagram to the
* 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 the
/ / Third and all remaining arguments and send that.
Byte [] message;
If (args [2]. Equals (the "-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 we've 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.getByName InetAddress address = (host);
/ / Initialize a datagram packet with data and address
DatagramPacket packet = new DatagramPacket (message, message.length,
Address, port);
/ / Create a datagram socket, and 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 datagrams sent the specified port.
* When it receives one, it displays the sending host and prints the
* The contents of the datagram 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 datagrams into. If anyone sends us a
/ / Packet containing more than will fit into this buffer, the
/ / 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 datagram
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, we'd just create a new packet each time.
Packet.setLength (buffer.length);
)
)
Catch (Exception e) (
System.err.println (e);
System.err.println (usage);
)
)
)
UDP in the main category is DatagramSocket () and DatagramPacket (), and in UDPreceive, to accept the byte is subject to restrictions as not feeling too good, since buf is a byte array, we wonder why it is very Construction not for its own investigation to the length of the array? We can only guess the reason is that the result of C programming style, where the arrayä¸èƒ½è‡ªå·±tell us how much it.






