Java socket programming and sample code _java

Source: Internet
Author: User

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 tools, and even peer-to-peer downloads are based on sockets. This article describes the TCP/IP based socket programming and how to write a client/server program.

Dessert before dinner

The UNIX input/output (IO) system follows the Open-read-write-close operation template. Before a user process does an IO operation, it needs to call open to specify and get permission to read or write to the file or device to be manipulated. Once the 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 operation object and pass the data to the user process. The write operation is used to pass (write) data from the user process to the IO Operation object. When all the read and write operations are finished, the user process needs to call close to notify the system that it is using the IO object.

When Unix begins to support interprocess communication (interprocess communication, or IPC), the interface of the IPC is designed to resemble the file IO operator interface. In Unix, a process has a set of IO descriptors that can read writes. The IO descriptor can be a file, a device, or a communication channel (socket socket). A file descriptor consists of three parts: creating (opening the socket), reading the write data (accepting and sending to the socket), and destroying (closing the socket).

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

A pair of sockets is required for interprocess communication operations. Interprocess communication is accomplished by data transfer between one socket in one process and another socket in another process. When a message executes, the message is queued in the socket on the sender side until the underlying network protocol sends the message. When the message reaches the socket at the receiving end, it is also queued until the receiving process receives the message.

TCP and UDP communications

About socket programming we have two kinds of communication protocols to choose from. One is datagram communication, the other is circulation letter.

Datagram Communication

Datagram communication protocol, is what we often say UDP (user data Protocol Users Datagram Protocol). UDP is a connectionless protocol, which means that each time we send the data, we need to send both the local socket descriptor and the socket descriptor at the receiving end. As a result, we need to send extra data each time we communicate.

Streaming communication

Stream communication protocol, also known as TCP (Transfer control Protocol, Transmission Control Protocol). Unlike UDP, TCP is a connection based protocol. Before using the letter of circulation, we must establish a connection between the two pairs of sockets in the communication. One of the sockets listens for a connection request as a server. The other is the connection request as a client. Once two sockets have been set up, they can transfer data either in one direction or in both directions.

Read here, how many of us have such a question, we do socket programming using UDP or TCP. The choice of socket programming based on what protocol depends on your specific client-server application scenario. Here's a quick look at the differences between TCP and UDP protocols, which may help you better choose which to use.

In UDP, each time the data is sent, the socket descriptor on the local computer and the socket descriptor on the receiving end are included. Because TCP is a connection based protocol, a connection is required between the socket pairs of the communication before communication, so there is a connection that is time-consuming in the TCP protocol socket programming.

In UDP, datagram data has a 64KB limit in size. There is no such restriction in TCP. Once the socket pairs of TCP communication are connected, communication between them is similar to IO flow, and all data is read in the order in which they are received.

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

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

Socket programming in Java

In the following sections I'll explain how to use sockets to write client and server-side programs.

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

Client Authoring

Open socket

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

String host = "127.0.0.1";
int port = 8919;
Socket client = new Socket (host, Port);

In the code above, the host is the machine that the client needs to connect to, and port is what the server uses to listen for the request. When selecting ports, 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 a port that is greater than 1023.

Write Data

The next step is to write the request data, we get the OutputStream object from the client's 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 = 8919;
    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

Similar to file Io, after reading and writing data is completed, we need to shut down the IO object to ensure the correct release of the resource.

Server-Side Authoring

Open the server-side socket

int port = 8919;
ServerSocket Server = new ServerSocket (port);
Socket socket = server.accept ();

The above code creates a server-side socket and then calls the Accept method to listen for and get the client's request socket. The Accept method is a blocking method that waits 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 read the data by installing file IO. 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) {
        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

Or you can't forget, finally you need to shut down the IO object properly to ensure the correct release of the resource.

Note An example

Here we add an example, using a socket to implement an echo server, that is, the server will send the client data back to the client. The code is simple.

Import java.io.*;
Import java.net.*; public class Echoserver {public static void main (String args[]) {//Declaration section://Declare a server s
    Ocket and a client socket for the server//declare an input and a output stream serversocket echoserver = null;
    String Line;
    DataInputStream is;
    PrintStream OS;
    Socket clientsocket = null; Try to open a server socket on port 9999//Note so we can ' t choose a port less than 1023 if we are not//PR
    Ivileged users (Root) try {echoserver = new ServerSocket (9999);
    catch (IOException e) {System.out.println (e);
    //Create A socket object from the ServerSocket to listen and accept//connections.
        Open input and output streams try {clientsocket = echoserver.accept ();
        is = new DataInputStream (Clientsocket.getinputstream ());
        OS = new PrintStream (Clientsocket.getoutputstream ()); As long as we receive data, Echo That data is back to the client.
         while (true) {line = Is.readline ();
        Os.println (line);
      The catch (IOException e) {System.out.println (e);
 }
    }
}

Compile and run the above code, and make the following request, you can see the content of the data that the client requests to carry.

15:00 $ curl http://127.0.0.1:9999/?111 get
/?111 http/1.1 user-agent:curl/7.37.1 host:127.0.0.1:9999
Accept: */*

Summarize

Client-server programming is still more interesting, while socket programming in Java is simpler and faster than in other languages, such as C.

Java.net This package contains a lot of powerful and flexible classes for developers to network programming, in the network programming, it is recommended to use the API below this package. At the same time sun.* This package also contains a lot of network programming related classes, but it is not recommended to use the API below the package, because this package may change, and the other package is not guaranteed to be included in all platforms.

The above is the Java socket data collation, follow-up continue to supplement the relevant knowledge, thank you for your support of this site!

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.