Java socket programming-single thread

Source: Internet
Author: User

I. Two main problems in Network Programming

One is how to accurately locate one or more hosts on the network, and the other is how to transmit data reliably and efficiently after finding the hosts.

In TCP/IP, the IP layer is mainly responsible for locating network hosts and routing data transmission. The IP address can uniquely identify a host on the Internet.

The TCP layer provides an application-oriented reliable (tcp) or non-reliable (UDP) data transmission mechanism, which is the main object of network programming, generally, you do not need to care about how the IP layer processes data.

Currently, the popular network programming model is the Client/Server (C/S) structure. That is, one Party serves as the server to wait for the customer to make a request and respond. The customer submits an application to the server when the service is required. The server is always running as a daemon and listens to the network port. Once a customer requests the server, a service process is started to respond to the customer. At the same time, the server continues to listen to the Service port, so that later customers can get services in a timely manner.

2. Two types of transmission protocols: TCP and UDP

TCPYesTranfer Control ProtocolIs a connection-oriented protocol for reliable transmission. It is transmitted over TCP to obtain a sequential error-free data stream. The sender and receiver must establish a connection between two pairs of sockets to facilitate communication based on the TCP protocol. When a socket (usually a server socket) is waiting to establish a connection, another socket can require a connection. Once the two sockets are connected, they can perform bidirectional data transmission, and both parties can send or receive data.

UDPYesUser datasync ProtocolThe abbreviation is a connectionless protocol. Each datagram is an independent information, including the complete source address or destination address. It is transmitted to the destination in any possible path on the network, therefore, whether or not to reach the destination, the time to arrive at the destination, and the correctness of the content cannot be guaranteed.

Comparison:

UDP:1. Complete address information is provided in each datagram, so there is no need to establish a connection between the sender and the receiver.

2. When UDP transmits dataYesThe size of each transmitted datagram must be limitedWithin 64 KB.

3. UDP is an unreliable protocol. The data packets sent by the sender do not necessarily arrive at the receiver in the same order.

TCP:1. For connection-oriented protocols, a connection must be established before data transmission between sockets. Therefore, connections must be established in TCP.

Time.

2. TCP transmission data size limit. Once the connection is established, the sockets of both parties can transmit large

Data.

3. TCP is a reliable protocol that ensures that the receiver fully and correctly obtains all data sent by the sender.

Application:

1,TCPStrong vitality in network communication, such as remote connection (Telnet) and file transmission (FTP) require data of an indefinite length to be reliably transmitted. However, reliable transmission requires a price. The test of the correctness of data content must take up the processing time and bandwidth of the computer,Therefore, TCP transmission is less efficient than UDP transmission..

2,UDPIt is easy to operate and requires less monitoring. Therefore, it is usually used for client/server applications in distributed systems with high LAN reliability. For example, a video conferencing system does not require that the audio and video data be absolutely correct. You only need to ensure consistency. In this case, UDP is obviously more reasonable.

Iii. Socket-based java Network Programming

1. What is Socket?

Two programs on the network exchange data through a two-way communication connection. one end of this two-way link is called a Socket. Socket is usually used to connect the customer and the service provider. Socket is a very popular programming interface of TCP/IP protocol. A Socket is uniquely identified by an IP address and a port number.

However, the Protocol types supported by the Socket are not only TCP/IP, so there is no necessary link between the two. In the Java environment, Socket programming mainly refers to network programming based on TCP/IP protocol.

2. Socket Communication Process

Server Listen (listener) whether a port has a connection request. The Client sends a Connect (connection) request to the Server, and the Server sends an Accept (Accept) message back to the Client. A connection is established. Both the Server and Client can communicate with each other by sending, writing, and other methods.

For a fully functional Socket, it must contain the following basic structure. The working process includes the following four basic steps:

(1) create a Socket;

(2) Open the input/output stream connected to the Socket;

(3) perform read/write operations on the Socket according to certain protocols;

(4) Disable Socket. (display close is not used in practical applications. Although this is recommended in many articles, in my program, it may be because the program itself is relatively simple and has low requirements, so there is no impact .)

3. Create a Socket

Create Socket

Java provides two types of Socket and ServerSocket in the java.net package, which are used to represent the client and server for two-way connection respectively. These are two encapsulated classes that are very convenient to use. The construction method is as follows:

Socket (InetAddress address, int port );

Socket (InetAddress address, int port, boolean stream );

Socket (String host, int prot );

Socket (String host, int prot, boolean stream );

Socket (SocketImpl impl)

Socket (String host, int port, InetAddress localAddr, int localPort)

Socket (InetAddress address, int port, InetAddress localAddr, int localPort)

ServerSocket (int port );

ServerSocket (int port, int backlog );

ServerSocket (int port, int backlog, InetAddress bindAddr)

Here, address, host, and port are the IP address, host name, and port number of the other side of the two-way connection. stream indicates whether the socket is a stream socket or a datagram socket. localPort indicates the port number of the local host, localAddr and bindAddr are the addresses of local machines (the host address of ServerSocket), and impl is the parent class of socket, which can be used to create both serverSocket and Socket. Count indicates the maximum number of connections supported by the server. Example: learning video network http://www.xxspw.com

Socket client = new Socket ("127.0.01.", 80 );

ServerSocket server = new ServerSocket (80 );

Note: Be careful when selecting a port. Each port provides a specific service. Only the correct port is provided to obtain the corresponding service. 0 ~ The port number of 1023 is retained by the system. For example, the port number of the http service is 80, the port number of the telnet service is 21, and the port number of the ftp service is 23, it is best to select a number greater than 1023 to prevent conflicts.

If an error occurs during socket creation, an IOException is generated and must be processed in the program. Therefore, exceptions must be caught or thrown when a Socket or ServerSocket is created.

4. Simple Client/Server programs

1. Client Program

Import java. io .*;

Import java.net .*;

Public class TalkClient {

Public static void main (String args []) {

Try {

Socket socket = new Socket ("127.0.0.1", 4700 );

// Send a customer request to port 4700 of the Local Machine

BufferedReader sin = new BufferedReader (new InputStreamReader (System. in ));

// The BufferedReader object is constructed by the system standard input device.

PrintWriter OS = new PrintWriter (socket. getOutputStream ());

// Obtain the output stream from the Socket object and construct the PrintWriter object

BufferedReader is = new BufferedReader (new InputStreamReader (socket. getInputStream ()));

// Obtain the input stream from the Socket object and construct the corresponding BufferedReader object

String readline;

Readline = sin. readLine (); // read a string from the system standard input

While (! Readline. equals ("bye ")){

// If the string read from the standard input is "bye", the loop is stopped.

OS. println (readline );

// Output the string read from the system standard input to the Server

OS. flush ();

// Refresh the output stream so that the Server receives the string immediately

System. out. println ("Client:" + readline );

// Print the read string on the system standard output

System. out. println ("Server:" + is. readLine ());

// Read a string from the Server and print it to the standard output.

Readline = sin. readLine (); // read a string from the system standard input

} // Continue the loop

OS. close (); // close the Socket output stream

Is. close (); // close the Socket input stream

Socket. close (); // close the Socket

} Catch (Exception e ){

System. out. println ("Error" + e); // the Error message is printed.

}

}

}

2. server programs

Import java. io .*;

Import java.net .*;

Import java. applet. Applet;

Public class TalkServer {

Public static void main (String args []) {

Try {

ServerSocket server = null;

Try {

Server = new serversockets (4700 );

// Create a ServerSocket to listen to customer requests on port 4700

} Catch (Exception e ){

System. out. println ("can not listen to:" + e );

// Error: print error message

}

Socket socket = null;

Try {

Socket = server. accept ();

// Use accept () to block waiting for customer requests.

// When the request arrives, a Socket object is generated and the execution continues.

} Catch (Exception e ){

System. out. println ("Error." + e );

// Error: print error message

}

String line;

BufferedReader is = new BufferedReader (new InputStreamReader (socket. getInputStream ()));

// Obtain the input stream from the Socket object and construct the corresponding BufferedReader object

PrintWriter OS = newPrintWriter (socket. getOutputStream ());

// Obtain the output stream from the Socket object and construct the PrintWriter object

BufferedReader sin = new BufferedReader (new InputStreamReader (System. in ));

// The BufferedReader object is constructed by the system standard input device.

System. out. println ("Client:" + is. readLine ());

// Print the string read from the client on the standard output

Line = sin. readLine ();

// Read a string from the standard input

While (! Line. equals ("bye ")){

// If the string is "bye", the loop is stopped.

OS. println (line );

// Output the string to the client

OS. flush ();

// Refresh the output stream so that the Client receives the string immediately

System. out. println ("Server:" + line );

// Print the read string on the system standard output

System. out. println ("Client:" + is. readLine ());

// Read a string from the Client and print it to the standard output.

Line = sin. readLine ();

// Read a string from the system standard input

} // Continue the loop

OS. close (); // close the Socket output stream

Is. close (); // close the Socket input stream

Socket. close (); // close the Socket

Server. close (); // close ServerSocket

} Catch (Exception e ){

System. out. println ("Error:" + e );

// Error: print error message

}

}

}

5. Support multi-client/server programs

The previous Client/Server program can only implement a conversation between the Server and a customer. In practical applications, a permanent program is often run on the server. It can receive requests from multiple other clients and provide corresponding services. In order to provide services to multiple customers on the server side, the above program needs to be transformed to implement multi-client mechanism using multithreading. The server always listens to the customer request on the specified port. Once the customer request is monitored, the server starts a special service thread to respond to the customer's request, the server itself enters the listening status immediately after the thread is started, waiting for the arrival of the next customer.

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.