Network programming: Talking about some simple applications of TCP and UDP

Source: Internet
Author: User
Tags final socket stringbuffer

The most important thing in network programming is the socket, which is actually the principle of the listening port. And the principle that we use mobile phones to send text messages should be roughly no two (I understand this), and Java's best point is "painless networking."

The most basic spirit of the network is to make two machines connected, "The caller" is the server, and the "one party" is called the client, so that in the connection of the server, the client is a relative concept. And our identification of the machine is mainly through the IP address and port to differentiate.

"Transmission Control Protocol" TCP and "User Datagram Protocol" are two different protocols, Java support for the two protocols are basically the same, and their own biggest difference is the reliability and speed of transmission, the former is a reliable protocol compared to the latter, of course, the latter is much faster, Below we use two sockets to demonstrate:

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 uses servers for unlimited listening, and clients is a client-sent program that uses 2000 of its ports.


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 ... \ n" +


"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 of the message to send.


//If The third argument is-f, then send the contents of the the file


//specified as the fourth argument. Otherwise, concatenate the


//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 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 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 datagram packet with data and address


datagrampacket packet = new Datagrampacket (message, Message.length,


address, Port);


//Create A datagram socket, 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.*;


   /**


* Waits to receive datagrams sent the specified port.


* When it receives one, it displays the sending host and prints 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" 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'll fit to this buffer, the


//excess would 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);


}


}


}

The main class in UDP is Datagramsocket () and datagrampacket (), whereas in Udpreceive, the accepted byte is restricted, and these feelings are not too good, since buf is a byte array, We are really wondering why the builder itself can't investigate the length of the array? The only reason to guess is that the C-style programming dictates that the array cannot tell us how big it is.

And we actually use the process, of course, not limited to these, which have to consider a number of clients to connect to the server, so to take into account threading thread use, if coupled with swing, you can do a similar to QQ socket function, This is limited to some of my insights when I'm learning sockets. For your reference.

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.