Java Socket Programming

Source: Internet
Author: User
Tags sin

One, the 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 reliably and efficiently transfer data when the host is found.

In the TCP/IP protocol, it is mainly responsible for the location of the network host, the routing of data transmission, and the IP address can uniquely determine a host on the Internet.

The TCP layer provides an application-oriented reliable (TCP) or unreliable (UDP) data transmission mechanism, which is the main object of network programming, and generally does not need to care about how the IP layer handles the data.

At present, the popular network programming model is the client/server (c/s) structure. That is, both sides of the communication are waiting for the client to request and respond as a server. The customer requests the server when the service is required. Server generally as a daemon always run, listen to the network port, once a customer request, will start a service process to respond to the customer, while continuing to monitor the service port, so that later customers can also be timely service.

Second, two types of transmission protocol: TCP;UDP

TCP is the short name of Tranfer Control protocol and is a connection-oriented protocol that guarantees reliable transmission. With the TCP protocol transmission, a sequential error-free data stream is obtained. A connection must be established between the sender and the receiver's paired two sockets to communicate on the basis of the TCP protocol, and when a socket (usually a server socket) waits for a connection, the other socket can require a connection. Once the two sockets are connected, they can carry out two-way data transfer and both can send or receive operations.

UDP is the abbreviation of User Datagram protocol, is a non-connected protocol, each datagram is a separate information, including the full source address or destination address, it on the network with any possible path to the destination, so can reach the destination, The time to reach the destination and the correctness of the content are not guaranteed.

Comparison:

Udp:1, the full address information is given in each datagram, so there is no need to establish a connection between the sender and the receiver.

        2,UDP传输数据时是有大小限制的,每个被传输的数据报必须限定在64KB之内。       3,UDP是一个不可靠的协议,发送方所发送的数据报并不一定以相同的次序到达接收方

Tcp:1, connection-oriented protocol, the connection must be established before data transfer between sockets, so connection in TCP is required

            时间。        2,TCP传输数据大小限制,一旦连接建立起来,双方的socket就可以按统一的格式传输大的                  数据。         3,TCP是一个可靠的协议,它确保接收方完全正确地获取发送方所发送的全部数据。

Application:

1,tcp has a strong vitality in network communications, such as remote Connection (Telnet) and file Transfer (FTP), which require the data to be reliably transmitted over an indefinite length. But reliable transmission is to pay a price, the correctness of the data content of the test must occupy the computer processing time and network bandwidth, so the efficiency of TCP transmission is not as high as UDP.

2,UDP is simple to operate and requires less monitoring, so it is often used in client/server applications in decentralized systems with high reliability for LANs. For example, the video conferencing system, does not require audio and video data is absolutely correct, as long as the consistency can be guaranteed, in this case, it is obvious that using UDP is more reasonable.

Third, socket-based Java network programming

1, what is a socket

The two programs on the network realize the exchange of data through a two-way communication connection, one end of this bidirectional link is called a socket. Sockets are typically used to connect clients and service parties. Sockets are a very popular programming interface for the TCP/IP protocol, and a socket is uniquely determined by an IP address and a port number.

However, the type of protocol supported by the socket is not only TCP/IP, so there is no necessary connection between the two. In the Java environment, socket programming mainly refers to the network programming based on TCP/IP protocol.

The process of 2,socket communication

Server side Listen (listening) a port has a connection request, the client sends a connect request to the server side, and the server sends back the Accept message to the client side. A connection is built up. Both the server side and client side can communicate with each other through methods such as Send,write.

For a full-featured socket, the following basic structure is included, and the work process consists of the following four basic steps:

(1) Create socket;

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

(3) Read/write the socket according to certain protocol;

(4) Close the socket. (In practice, the displayed close is not used, although many articles recommend this, but in my program, it may be because the program itself is relatively simple, the requirements are not high, so there is no impact.) )

3, create socket

Create socket

Java provides two classes of sockets and ServerSocket in Package java.net, respectively, to represent the client and server side of a two-way connection. This is a two well-packaged class that is very handy to use. The method is constructed 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)

Where address, host, and port are the IP address, hostname, and port number of the other side of the two-way connection, stream indicates whether the socket is a stream socket or datagram Socket,localport represents the port number of the local host, LOCALADDR and BINDADDR is the address of the local machine (ServerSocket's host address), Impl is the parent of the socket and can be used to create serversocket and to create sockets. Count indicates the maximum number of connections that can be supported by the server. For example: Learning video Network http://www.xxspw.com

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

ServerSocket Server = new ServerSocket (80);

Note that you must be careful when choosing a port. Each port provides a specific service, and only the correct port is given to obtain the appropriate service. The port number of the 0~1023 is reserved for the system, such as the port number of the HTTP service for the 80,telnet service port number is 23, so when we select the port number, it is best to select a number greater than 1023 to prevent a conflict.

If an error occurs when creating the socket, IOException will be generated and must be handled in the program. So when creating sockets or ServerSocket, you must catch or throw exceptions.

4, Simple Client/server program

    1. Client programs

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);

Shanben 4700 port to make customer requests

BufferedReader sin=new BufferedReader (New InputStreamReader (system.in));

Constructing BufferedReader objects from System standard input devices

PrintWriter os=new PrintWriter (Socket.getoutputstream ());

The output stream is obtained by the socket object, and the PrintWriter object is constructed

BufferedReader is=new BufferedReader (New InputStreamReader (Socket.getinputstream ()));

The input stream is obtained by the socket object and the corresponding BufferedReader object is constructed

String ReadLine;

Readline=sin.readline (); Reads a string from the system standard input

while (!readline.equals ("Bye")) {

Stop looping if the string read in from standard input is "bye"

Os.println (ReadLine);

Output a string read from the system standard input to the server

Os.flush ();

Refreshes the output stream so that the server receives the string immediately

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

Print the read-in string on the system standard output

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

Reads a string from the server and prints it to the standard output

Readline=sin.readline (); Reads a string from the system standard input

}//Resume loop

Os.close (); Close the socket output stream

Is.close (); Close the socket input stream

Socket.close (); Close socket

}catch (Exception e) {

System.out.println ("Error" +e); Error, print error message

}

}

}

2. Server-side 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 ServerSocket (4700);

Create a ServerSocket to listen for customer requests on port 4700

}catch (Exception e) {

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

Error, printing error message

}

Socket Socket=null;

try{

Socket=server.accept ();

Use the Accept () block to wait for a customer request, a customer

When the request arrives, a socket object is generated and the execution continues

}catch (Exception e) {

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

Error, printing error message

}

String Line;

BufferedReader is=new BufferedReader (New InputStreamReader (Socket.getinputstream ()));

The input stream is obtained by the socket object and the corresponding BufferedReader object is constructed

PrintWriter Os=newprintwriter (Socket.getoutputstream ());

The output stream is obtained by the socket object, and the PrintWriter object is constructed

BufferedReader sin=new BufferedReader (New InputStreamReader (system.in));

Constructing BufferedReader objects from System standard input devices

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

Print a string read from the client on standard output

Line=sin.readline ();

Reads a string from a 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 ();

Refreshes the output stream so that the client receives the string immediately

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

Print the read-in string on the system standard output

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

Reads a string from the client and prints it to the standard output

Line=sin.readline ();

Reads a string from the system standard input

}//Resume loop

Os.close (); Close the socket output stream

Is.close (); Close the socket input stream

Socket.close (); Close socket

Server.close (); Close ServerSocket

}catch (Exception e) {

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

Error, printing error message

}

}

}

5, support multi-client Client/server program

The previous Client/server program can only implement a conversation between the server and a client. In practice, it is often a permanent program running on the server that can receive requests from multiple clients and provide the appropriate services. In order to realize the function of serving multiple customers in the server side, the above program needs to be reformed and multi-client mechanism can be realized by multithreading. The server always listens for customer requests on the specified port, and once it listens to a customer request, the server initiates a dedicated service thread to respond to the customer's request, and the server itself enters the listening state immediately after the thread is started, waiting for the next customer to arrive.

Java Socket Programming

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.