Socket programming in Java

Source: Internet
Author: User
Tags sin

Socket, also known as socket, socket is one of the basic technologies of computer network communication. Today, most web-based software, such as browsers, instant messaging, and even peer-download, is based on sockets. This article describes TCP/IP-based socket programming and how to write a client/server program.

The UNIX input-output (IO) system follows the Open-read-write-close model. Before a user process makes an IO operation, it needs to call open to specify and obtain the permission to be read or written by the file or device to be manipulated. Once an IO operation object is opened, the user process can read or write to the object one or more times. The read operation is used to read data from an IO operand and pass the data to the user process. The write operation is used to pass (write) data from the user's process to the IO action object. When all the read and write operations are finished, the user process needs to call close to notify the system of its completion of the use of the IO object.

When Unix begins to support interprocess communication (interprocess communication, or IPC), the IPC interface is designed to be similar to the file IO operation interface. In Unix, a process has a set of IO descriptors that can read and write. The IO descriptor can be a file, a device, or a communication channel (socket socket). A file descriptor consists of three parts: create (open socket), read write data (accept and send to socket) and destroy (Close socket).

In Unix systems, the BSD-like version of the IPC interface is implemented as a layer above the TCP and UDP protocols. The destination of the message is represented using the socket address. A socket address is a communication identifier that consists of a network address and a port number.

An inter-process communication operation requires a pair of sockets. interprocess communication is done by transferring data from one socket to another in one process to another. When a message executes, the message is queued in the socket on the sending side until the underlying network protocol sends the messages. When the message arrives at the receiving end of the socket, it is also queued until the receiving side processes the message.

TCP and UDP communication

About socket programming There are two types of communication protocols that can be selected. One is the datagram communication, the other is the circulating letter.

Datagram Communication

The datagram communication protocol is what we often call UDP (user Data Protocol Subscriber Datagram Protocol). UDP is a non-connected protocol, which means that each time we send a datagram, we need to send both the socket descriptor of the machine and the socket descriptor at the receiving end. Therefore, we need to send extra data each time we communicate.

Stream communication

The stream communication protocol, also known as TCP (Transfer Control Protocol, Transmission protocol). Unlike UDP, TCP is a connection-based protocol. Before using a flow of letters, we must establish a connection between the communication's pair of sockets. One of the sockets listens for connection requests as a server. The other is a connection request as a client. Once the two sockets have been established, they can transmit data in one or both directions.

Read here, how much we have this question, we do socket programming using UDP or TCP it. The choice of the protocol based socket programming depends on your specific client-server application scenario. Let's briefly analyze the differences between TCP and UDP protocols, perhaps to help you better choose which one to use.

In UDP, each time a datagram is sent, it needs to be accompanied by the socket descriptor on the computer and the socket descriptor on the receiving side. Because TCP is a connection-based protocol, there is a need to establish a connection between the socket pairs of the communication before the communication, so there is a time-consuming socket programming that exists in the TCP protocol.

In UDP, datagram data has a 64KB limit on size. There is no such restriction in TCP. Once the TCP communication socket pair establishes a connection, the communication between them is similar to the IO stream, and all the data is read in the order in which it was received.

UDP is an unreliable protocol that sends datagrams that are not necessarily accepted by the socket at the receiving end in the order in which they are sent. Then TCP is a reliable protocol. The order of packets received by the receiving end is consistent with the order of the packets on the sending side.

In short, TCP is suitable for network services such as remote login (rlogin,telnet) and file Transfer (FTP). Because the size of the data that needs to be transferred is indeterminate. UDP is simpler and lighter than TCP. UDP is used to achieve higher real-time or packet loss is not important for some services. UDP packet loss rate is relatively low in LAN.

  • Home
  • All articles
  • Information
  • Web
  • Architecture
  • Basic technology
  • Books
  • Tutorial
  • I want to contribute
  • More channels»
-Navigation Bar-HomeAll articlesInformationWebArchitectureBasic technologyBooksTutorialI want to contributeMore channels»-IOS-Python-Android-Web Front EndRead socket programming in Java

2015/03/09 | Category: Basic Technologies | 2 Reviews | Tags: SOCKET

Share to:Source: Androidyue Source: Qusay H. Mahmoud

Socket, also known as socket, socket is one of the basic technologies of computer network communication. Today, most web-based software, such as browsers, instant messaging, and even peer-download, is based on sockets. This article describes TCP/IP-based socket programming and how to write a client/server program.

Pre-dinner Dessert

The UNIX input-output (IO) system follows the Open-read-write-close model. Before a user process makes an IO operation, it needs to call open to specify and obtain the permission to be read or written by the file or device to be manipulated. Once an IO operation object is opened, the user process can read or write to the object one or more times. The read operation is used to read data from an IO operand and pass the data to the user process. The write operation is used to pass (write) data from the user's process to the IO action object. When all the read and write operations are finished, the user process needs to call close to notify the system of its completion of the use of the IO object.

When Unix begins to support interprocess communication (interprocess communication, or IPC), the IPC interface is designed to be similar to the file IO operation interface. In Unix, a process has a set of IO descriptors that can read and write. The IO descriptor can be a file, a device, or a communication channel (socket socket). A file descriptor consists of three parts: create (open socket), read write data (accept and send to socket) and destroy (Close socket).

In Unix systems, the BSD-like version of the IPC interface is implemented as a layer above the TCP and UDP protocols. The destination of the message is represented using the socket address. A socket address is a communication identifier that consists of a network address and a port number.

An inter-process communication operation requires a pair of sockets. interprocess communication is done by transferring data from one socket to another in one process to another. When a message executes, the message is queued in the socket on the sending side until the underlying network protocol sends the messages. When the message arrives at the receiving end of the socket, it is also queued until the receiving side processes the message.

TCP and UDP communication

About socket programming There are two types of communication protocols that can be selected. One is the datagram communication, the other is the circulating letter.

Datagram Communication

The datagram communication protocol is what we often call UDP (user Data Protocol Subscriber Datagram Protocol). UDP is a non-connected protocol, which means that each time we send a datagram, we need to send both the socket descriptor of the machine and the socket descriptor at the receiving end. Therefore, we need to send extra data each time we communicate.

Stream communication

The stream communication protocol, also known as TCP (Transfer Control Protocol, Transmission protocol). Unlike UDP, TCP is a connection-based protocol. Before using a flow of letters, we must establish a connection between the communication's pair of sockets. One of the sockets listens for connection requests as a server. The other is a connection request as a client. Once the two sockets have been established, they can transmit data in one or both directions.

Read here, how much we have this question, we do socket programming using UDP or TCP it. The choice of the protocol based socket programming depends on your specific client-server application scenario. Let's briefly analyze the differences between TCP and UDP protocols, perhaps to help you better choose which one to use.

In UDP, each time a datagram is sent, it needs to be accompanied by the socket descriptor on the computer and the socket descriptor on the receiving side. Because TCP is a connection-based protocol, there is a need to establish a connection between the socket pairs of the communication before the communication, so there is a time-consuming socket programming that exists in the TCP protocol.

In UDP, datagram data has a 64KB limit on size. There is no such restriction in TCP. Once the TCP communication socket pair establishes a connection, the communication between them is similar to the IO stream, and all the data is read in the order in which it was received.

UDP is an unreliable protocol that sends datagrams that are not necessarily accepted by the socket at the receiving end in the order in which they are sent. Then TCP is a reliable protocol. The order of packets received by the receiving end is consistent with the order of the packets on the sending side.

In short, TCP is suitable for network services such as remote login (rlogin,telnet) and file Transfer (FTP). Because the size of the data that needs to be transferred is indeterminate. UDP is simpler and lighter than TCP. UDP is used to achieve higher real-time or packet loss is not important for some services. UDP packet loss rate is relatively low in LAN.

Socket programming in Java

In the following sections I'll walk through some examples of how to write client and server-side programs using sockets.

Note: In the next example, I will use the TCP/IP protocol-based socket programming because this protocol is far more extensive than UDP/IP. And all of the socket related classes are located under the java.net package, so we need to introduce this package when we do socket programming.

Client Write Open socket

If on the client side, you need to write down the following code to open a socket.

String host = "127.0.0.1"; int port = 8080; Socket client = new socket (host, port);

In the above code, host is the machine that the client needs to connect to, and port is the one on the server that listens for requests. When choosing a port, it is important to note that 0~1023 these ports are already reserved by the system. These ports are used by a number of commonly used services, such as mail, FTP, and HTTP. When you are writing server-side code, select the port, select a port greater than 1023.

Write Data

The next step is to write the request data, we get the OutputStream object from the client socket object, and then write the data. Very similar to file IO processing code.

public class Clientsocket {  public static void Main (String args[]) {         string host = "127.0.0.1";         int port = 8080;         try {          socket Client = new Socket (host, port);           writer Writer = new OutputStreamWriter (Client.getoutputstream ());           Writer.write ("Hello from Client");           writer.flush ();           writer.close ();           client.close ();         } catch ( IOException e) {          e.printstacktrace ();         }    } } 
Close IO Object

Like file Io, after the read and write data is completed, we need to close the IO object to ensure the correct release of the resource.

Server-side write open the server-side socket
int port = 8080; ServerSocket Server = new ServerSocket (port); Socket socket = server.accept ();

The code for the polygon creates a server-side socket, and then calls the Accept method to listen and get the client's request socket. The Accept method is a blocking method that waits for blocking until a connection is established between the server side and the client.

Reading data

Get the InputStream object from the socket object above and then install file IO to read the data. Here we print out the content.

public class Serverclient {  public static void main (string[] args) {         int Port = 8919;        try {             serversocket Server = new ServerSocket (port);                 socket Socket = server.accept ();             reader Reader = new InputStreamReader ( Socket.getinputstream ());             char chars[] = New Char[1024];            int len;             stringbuilder builder = new StringBuilder ();             while ((Len=reader.read (chars))! =-1) {   &nBsp;            builder.append (New String (chars, 0, Len));            }             system.out.println ("Receive from client message=:" + builder);             reader.close ();             socket.close ();             server.close ();         } catch (Exception E ) {            e.printstacktrace ();         }  }}
Close IO Object

Still cannot be forgotten, finally need to close the IO object properly to ensure the correct release of resources.

  

Comes with a client example

package socket;import java.io.bufferedreader;import java.io.IOException; Import Java.io.inputstreamreader;import Java.io.printwriter;import Java.net.socket;import Java.net.unknownhostexception;public class Client {public static void main (string[] args) {try {//Shanben port send request socket socket= New Socket ("127.0.0.1", 8080);//BufferedReader object constructed by the system standard input device BufferedReader sin=new BufferedReader (new InputStreamReader (system.in));//construct the output stream object PrintWriter pw=new printwriter (Socket.getoutputstream ());//The input stream is obtained by the socket object , and constructs the corresponding BufferedReader object BufferedReader is=new BufferedReader (New InputStreamReader (Socket.getinputstream ())); String readline;//Read Data readline=sin.readline (); while (! readline.equals ("Bye")) {//Print input information pw.println (readline);// Real-time refresh Pw.flush (); System.out.println ("Client:" +readline); System.out.println ("Server:" +is.readline ());} Pw.close (); Is.close (); Socket.close ();} catch (Unknownhostexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}}} 

  

  

 

  

Socket programming in Java

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.