TCP/UDP Socket Java Socket Programming instance

Source: Internet
Author: User

Network protocol seven-tier structure:

What is a socket?

The socket (socket) is the end of the two-program data exchange between the two-way channel, which can be understood as an interface. Using socket programming is also known as network programming, and sockets are just interfaces that are not network communication protocols.

The difference between the HTTP protocol and the socket

The HTTP protocol is the application layer, its pattern is request-reply, the client sends the request, the server side responds. The transmitted data is in the original format of the data, Eg:json, XML, text and other data formats.

Socket is not a protocol is an interface, socket provides an instance of TCP/UDP socket, for Java or other language operation data transmission, socket is the Transport layer (TCP/UPD Protocol) encapsulation.

Socket communication is divided into two types

TCP sockets: Use stream transport to provide inputstream and OutputStream methods for streaming data. To understand TCP sockets, you should first understand the TCP protocol.

1) The TCP protocol is the transport layer of the Protocol, his next layer is the IP Protocol (network layer), IP protocol in the network data transmission is through IP addressing, the source address and destination address to connect. The TCP protocol is an additional layer of port addressing on the IP protocol, where the light is only addressed to the host by IP addressing, and TCP finds the corresponding application via the port.

2) TCP establishes a connection that requires three handshakes, a connection between the source application and the destination application, so that the source application and the destination application must be a single by one. IP protocol just data transmission, does not guarantee that the data is lost, repeated transmission, the order is correct, TCP will make some compensation mechanism for these problems, lost data retransmission, with the queue to ensure the order of data.

3) TCP disadvantage: Because each client and server-side transmission of data to establish a connection, three handshake is not transmitting data and time-consuming, when there are a large number of short connections and the correctness of the data is not high, it will occupy the bandwidth.

UDP socket: Use data packets for transmission, create UDP socket to send and receive data packets.

1) UDP protocol is the same as the TCP protocol is the application layer protocol, but also through the port addressing, to find the corresponding application.

2) The UDP transmission data message does not need to establish a connection with the destination application, he specifies the destination host and the destination port number in the data message, and sends the data automatically addressed to the corresponding host and port number. Because there is no connection to the destination host, a source application can broadcast the datagram to multiple hosts in the form of broadcasts. Because there is no connection, time consuming and bandwidth consumption are better than the TCP protocol

3) UDP Disadvantage: Data may be lost, lost data will not be re-transmitted

Java Socket Instance

TCP Socket Client

 Packagesocket.transmission.tcp;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.Socket;//The TCP socket client is responsible for sending the request Public classTcpClient {Private Static  Final  intBuf_size=32; /*** There are three steps for a TCP client to send a request: * 1. Create an instance of a socket, create a TCP connection to the server host IP and port number * 2. Communication via socket input and output stream * 3. Using the SOC Ket Close*/     Public Static voidMain (string[] args) {String IP= "192.168.197.1"; intport=8080; Try {            //Create a Socket instanceSocket socket=NewSocket (Ip,port); System.out.println ("Create a socket connection"); InputStream InputStream=Socket.getinputstream (); OutputStream OutputStream=Socket.getoutputstream (); //writing data to the socketOutputstream.write ("This is a word". GetBytes ()); inttotalbyrecive=0;//data received so far            byte[] readbuff=New byte[Buf_size]; intLastreadbyte;//the last bytes receivedSYSTEM.OUT.PRINTLN ("Data received from the server:"); intreceivemsgsize;  while((Receivemsgsize=inputstream.read (readbuff))!=-1) {System.out.println (NewString (Readbuff));  } socket.close (); //Close}Catch(IOException e) {e.printstacktrace (); }    }}

TCP Sokect Server

 Packagesocket.transmission.tcp;//receiving requests on the TCP server sideImportSun.java2d.pipe.OutlineTextRenderer;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.ServerSocket;ImportJava.net.Socket;Importjava.net.SocketAddress;/*** The following processing is handled by the TCP server for requests sent to the client * 1. Create a ServerSocket instance and specify a native port, function: Listen for connections sent over a specified port * 2. Repeat: * 1). Call the ServerSocket's accept ( Listen to the request sent by the client and create the socket * 2). Use the socket's InputStream and OutputStream for communication * 3). End of communication use the Socket.close () method to close the connection*/ Public classTCPServer {Private Static  Final  intBuf_size=32;  Public Static voidMain (string[] args) {intport=8080; Socket Socket=NULL; InputStream InputStream=NULL; OutputStream OutputStream=NULL; Try{serversocket ServerSocket=NewServerSocket (port);//Create a socket instance to listen for connections sent by the clientSystem.out.println ("Create ServerSocket instance"); intRevicemsgsize;//the size of the received MSG            byte[] receivebuf=New byte[Buf_size];//create a buffer for receiving informationSystem.out.println ("Start processing received data");  while(true) {Socket= Serversocket.accept ();//receiving connections from clientsSocketAddress socketaddress = socket.getremotesocketaddress ();//SYSTEM.OUT.PRINTLN ("Access address:" +socketaddress); InputStream=Socket.getinputstream (); OutputStream=Socket.getoutputstream ();  while((Revicemsgsize = Inputstream.read (receivebuf))! =-1) {System.out.println (NewString (RECEIVEBUF)); Outputstream.write ("AAAAA". GetBytes (), 0, 4);                    } outputstream.flush ();                Socket.close (); }        } Catch(IOException e) {e.printstacktrace (); }finally {                Try {                    if(socket!=NULL) {socket.close (); }                    if(inputstream!=NULL) {inputstream.close (); }                    if(outputstream!=NULL) {outputstream.close (); }                } Catch(IOException e) {e.printstacktrace (); }        }    }}

TCP/UDP Socket Java Socket Programming instance

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.