Java Network programming TCP, UDP

Source: Internet
Author: User

Java Network Programming provides two types of protocols: TCP (Transmission Control Protocol) and UDP (Datagram protocol). TCP (transmission Control Protocol) is a reliable transport protocol that uses the "three-time handshake" side to establish a connection to ensure data reliability and security, while UDP (User Datagram PROTOCOL) protocol is an unreliable transmission protocol, the data sent is not necessarily acceptable to the online chat is the tool generally adopted this Protocol. The following will detail the use of TCP and UDP and the corresponding encoding.

One, TCP network communication
TCP is implemented in Java using a socket (socket). The server side uses the ServerSocket class, which is implemented by the client using the socket class.

1, ServerSocket class
It mainly has the following methods:

ServerSocket () Creates a non-binding server socket.
ServerSocket (int port) creates a server socket bound to a specific port.

The socket accept () listens for and accepts connections to this socket.
void Close () to close this socket
Boolean isClosed () returns the closed state of the serversocket.
InetAddress getinetaddress () returns the local address of this server socket.
void bind (socketaddress endpoint) binds serversocket to a specific address (IP address and port number).
Boolean Isbound () returns the binding state of the ServerSocket.
SocketAddress getlocalsocketaddress () returns the address of the endpoint of this socket binding and returns NULL if it is not already bound.

Server-side each run is to use the Accept () method to wait for the client's connection, after this method executes the server side will go into a blocking state, know the client connection after the program continues to execute, this method returns a socket, representing a client object.

2. Socket class
Two machines connect to the endpoint of the communication. The main use of the following methods:

The socket (String host, int port) creates a stream socket and connects it to the specified port number on the specified host.
OutputStream Getoutputstream () returns the output stream for this socket.
InputStream getInputStream () returns the input stream for this socket.
Boolean Isbound () returns the binding state of the socket.
Boolean isClosed () returns the closed state of the socket.
Boolean isconnected () returns the connection state of the socket.
void Close () closes this socket.
It communicates through the byte stream and the service side.

Example one, the following is the implementation of a simple TCP client server-side communication.
(1) Server side:
Package Andy.network.test;import Java.io.ioexception;import Java.io.printstream;import java.net.ServerSocket; Import java.net.socket;/**   * @author zhang,tianyou   * version:2014-11-25 morning 10:49:11   *  *   */public Class Firsttcpserver {/** * @param args * @throws ioexception  */public static void Main (string[] args) throws Ioexcept Ion {//creation server ServerSocket server = null; Socket socket = NULL; PrintStream out = null;//server waits on 9999 for client Access server = new ServerSocket (9999); SYSTEM.OUT.PRINTLN ("Server side already running, waiting for customer response ... ");//program block waits for the client to access socket = Server.accept ();//Output message to client string str =" Hello Andy. "; o UT = new PrintStream (Socket.getoutputstream ()); Out.print (str); Out.close (); Socket.close (); Server.close ();}}

(2) Client:
Package Andy.network.test;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import java.net.socket;import java.net.unknownhostexception;/** * @author Zhang,Tianyou  * version:2014-11-25 Morning 11:02:17 *  *  */public class Firsttcpsocket {/** * @param args * @throws IOException * @throws unknownhostexception */public static void Main (string[] args) throws Unknownhostexception,ioexception {// Define Client Socket clients = null;//Set address and port client = new Socket ("localhost", 9999); BufferedReader buf = null; End Service End Stream buf = new BufferedReader (New InputStreamReader (Client.getinputstream ())); String str = buf.readline (); SYSTEM.OUT.PRINTLN ("Server-side notification message:" + str); Buf.close (); Client.close ();}}

Example Two
To enable client and server-side communication, the server can respond to multiple clients, and each client request initiates a thread.

(1) Service side
Package Andy.network.test;import Java.io.ioexception;import java.net.serversocket;import java.net.Socket;/** * @  Author Zhang,tianyou  * version:2014-11-25 Morning 11:41:22 *  *         Chat server-side */public class Chatserver {/** * @param args * @throws ioexception */public static void Main (string[] args) throws IOException {ServerSocket server = null; Socket client = null;//listening on 9999 port connection server = new ServerSocket (9999); Boolean  flag = True;while (flag) {System.out.print ln (the server is running, waiting for the client to connect.) "); client = Server.accept ();//The new thread (new Chatthread (client)) is started on each of the clients ' requests. Start (); Server.close ();}}

Corresponding Service thread tasks:
Package Andy.network.test;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Java.io.printstream;import java.net.socket;/** * @author zhang,tianyou * version:2014-11-25 11:24:26 * * Use multithreading Mechanism to start a new task after each user response * */public class Chatthread implements Runnable {//Accept client private Socket clients = Null;public Chatthre AD (Socket client) {this.client = client;} @Overridepublic void Run () {//Send data to client printstream out = null;//receives data from client BufferedReader buff = null;try {//Get client input information bu FF = new BufferedReader (New InputStreamReader (Client.getinputstream ())); out = new PrintStream (Client.getoutputstream ( );//Flag Whether a client operation is complete Boolean flag = True;while (flag) {//constant receive information string str = Buff.readline (); if (str = = NULL | | "". Equals (str)) {flag = false;//client operation ends}else{if ("Bye". Equals (str)) {flag = False;out.println ("Bye-bye");} else {//Echo input out.println to client ("You input:" + str);}} Out.close (); Client.close ();} catch (Exception e) {System.out.println ("Server Exception! "); }}}

(2) Client
Package Andy.network.test;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.printstream;import Java.net.socket;import java.net.UnknownHostException ;/** * @author zhang,tianyou * version:2014-11-25 11:53:03 * * Chat client program * */public class ChatClient {public St atic void Main (string[] args) throws Unknownhostexception,ioexception {Socket client = Null;client = new Socket ("localhost ", 9999);//Receive server-side information BufferedReader buff = null;//sends data to the server printstream out = null; BufferedReader input = null;//get keyboard input data input = new BufferedReader (new InputStreamReader (system.in)); out = new PrintStream (Client.getoutputstream ()); buff = new BufferedReader (New InputStreamReader (Client.getinputstream ()));//Flag bit Boolean Flag = True;while (flag) {System.out.println ("Input information:"); String str = Input.readline ();//output Information out.println (str) to server side, if ("Bye". Equals (str)) {flag = false;} else {String Chatcont = Buff.readline (); System.out.println (Chatcont);}} Client.close(); Buff.close ();}} 

Second, UDP network communication
TCP communication is based on reliable communication, UDP is unreliable communication, the use of datagram form to send data.
In Java there are mainly Datagrampacket and Datagramsocket implementations.

1. Main methods of Datagrampacket
Datagrampacket (byte[] buf, int length)
Constructs a datagrampacket to receive packets of length.
Datagrampacket (byte[] buf, int length, inetaddress address, int port)
Constructs a datagram package that is used to send a package length to a specified port number on a specified host.
Byte[] GetData ()
Returns the data buffer.
int GetLength ()
Returns the length of the data that will be sent or received.

2. Main methods of Datagramsocket
Datagramsocket (int port)
Creates a datagram socket and binds it to the specified port on the local host.
void receive (Datagrampacket p)
Receives a datagram packet from this socket.
void Send (Datagrampacket p)
Sends a datagram packet from this socket.
When using UDP, you first use the client to specify the data and port to accept. Then turn on the server to send the data.

The implementation is as follows:
(1) Client
Package Andy.network.test;import Java.io.ioexception;import Java.net.datagrampacket;import java.net.DatagramSocket ;/** * @author zhang,tianyou  * version:2014-11-25 PM 3:04:10 *  *         UDP client */public class UdpClient {/** * @param args * @throws ioexception */public static void Main (string[] args) throws IOException {//customer listens on port 9999 Datagramsocket Dsock ET = Null;dsocket = new Datagramsocket (9999);//defines the byte length of the received data byte[] buff = new byte[1024];D atagrampacket dpacket = null;//means The length of the received data is 1024dPacket = new Datagrampacket (buff, 1024); System.out.println ("Wait for data to be accepted. ");//Receive Data dsocket.receive (Dpacket);  String str = new String (Dpacket.getdata (), 0, Dpacket.getlength ()) + "from" + dpacket.getaddress (). Gethostaddress () + ":" + Dpacket.getport (); System.out.println (str);//Closed Datagram socket Dsocket.close ();}}

(2) server-side

Package Andy.network.test;import Java.io.ioexception;import Java.net.datagrampacket;import java.net.DatagramSocket Import java.net.inetaddress;/**   * @author zhang,tianyou   * version:2014-11-25 pm 3:13:38   *  * UDP server side *   */public class Udpserver {/** * @param args * @throws ioexception  */public static void Main (string[] args) throws IOException {Datagramsocket Dsocket = null;//server is listening on port 3333 dsocket = new Datagramsocket (3333);D atagrampacket dPacket = nul l;//the data to occur string str = "Hello andy!"; /Send datagram to destination port address Dpacket = new Datagrampacket (Str.getbytes (), Str.length (), Inetaddress.getbyname ("localhost"), 9999); SYSTEM.OUT.PRINTLN ("Send Datagram"); Dsocket.send (Dpacket);d socket.close ();}}







Java Network programming TCP, UDP

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.