Java Network Programming Summary __ algorithm

Source: Internet
Author: User
Tags thread class

Summary of Java Network programming

In this paper, the Java Network Programming socket (socket) interface for the use of a detailed introduction and use.

A Two major problems in network programming

One is how to accurately locate the network on one or more hosts, and the other is to find the host after the reliable and efficient data transmission.

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

The TCP layer provides reliable (TCP) or unreliable (UDP) data transmission mechanisms for applications.

This is the main object of network programming, generally do not need to care about how the IP layer handles data.

At present, the more popular network programming model is client/server (c/s) structure.

That is, both sides of the communication wait for the customer to request and respond as a server.

The customer applies to the server when the service is needed.

The server is always running as a daemon, listening to network ports, and once a client requests it,

will start a service process to respond to the customer, at the same time continue to listen to the service port, so that later customers can also be timely access to services.



Two. Two class transport protocol: TCP;UDP


TCP is the abbreviation of Tranfer Control Protocol, is a connection-oriented protocol to ensure reliable transmission.

Through the TCP protocol transmission, obtains is a sequential error-free data stream.

A connection must be established between the pair of two sockets between the sender and the receiver.

To communicate on the basis of a TCP protocol, when a socket (usually a server socket) waits for a connection to be established,

Another socket can require a connection, once the two sockets are connected,

They can carry out two-way data transmission, both can send or receive operations.


UDP is the abbreviation of User Datagram protocol, is a connectionless protocol,

Each datagram is a separate piece of information, including a complete source address or destination address, which is transmitted to the destination on any possible path on the network,

Therefore, the arrival of the destination, the time to arrive at the destination and the correctness of the content are not guaranteed.


(i) Comparison: UDP and TCP


Udp:

1. 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 data transmission is limited in size, each transmitted datagram must be limited to 64KB.

3.UDP is an unreliable protocol in which datagrams sent by the sender do not necessarily reach the receiver in the same order


Tcp:

1. Connection-oriented protocol, before the data transmission between the socket is bound to establish a connection, so in the TCP need to connect time.

2.TCP Transmission data size limit, once the connection is established, both sides of the socket can be in uniform format transmission of large data.

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



(ii) Application:


1.TCP has very strong vitality in network communication,

For example, remote connection (Telnet) and file transfer (FTP) require indefinite length of data to be transmitted reliably.

But the reliable transmission has to pay the price, to the data content correctness examination must occupy the computer processing time and the network bandwidth,

Therefore TCP transmission efficiency is not as high as UDP.


2.UDP is simple to operate and requires less monitoring,

Therefore, it is usually used for client/server applications in decentralized systems with high reliability of LAN.

Video conferencing systems, for example, do not require audio and video data to be absolutely correct, as long as consistency is ensured,

In this case, it is obviously more reasonable to use UDP.

Three Java network programming based on socket


(i) Definition of socket


Two programs on the network realize the exchange of data through a two-way communication connection, one end of this two-way link is called a socket.

The socket is typically used to implement a connection between the client and the service party. Socket is a very popular programming interface of TCP/IP protocol,

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 connection between the two.

In the Java environment, socket programming mainly refers to the network programming based on TCP/IP protocol.



(b) The process of socket communication


Server-side Listen (listening) whether a port has a connection request, the client side sends a connect (connection) request to the server side,

The server side sends back accept (accept) messages to the client side. A connection is established.

Both the server end and the client side can communicate with each other through Send,write (Socket.getoutputstream/socket.getinputstream) methods.

For a fully functional socket, include the following basic structure, which includes the following four basic steps:

1. Create socket;

2. Open the input/out stream connected to the socket;

3. According to a certain agreement to the socket for read/write operations;

4. Close the socket. (In practice, not to use the display of closed, although many articles are recommended, but in my program, because the program itself is relatively simple, the requirements are not high, so did not cause any impact.) )




(iii) Create a socket


Creating a socket provides two classes of sockets and ServerSocket in the Java package java.net.

Used to represent the client and service side of a two-way connection. This is one of two very good packaged classes and is easy to use. The method is constructed as follows:


Constructor for client class:

Socket (inetaddress address, int port);

Socket (inetaddress address, int port, Boolean stream);

Socket (String host, int prot); Mainly used

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)

  

Constructors for service-side classes:

ServerSocket (int port); Mainly used

ServerSocket (int port, int backlog);

ServerSocket (int port, int backlog, inetaddress bindaddr)



Where address, host, and port are the IP addresses, host names, and port numbers of the other side of the two-way connection, stream indicates whether the socket is a stream socket or datagram Socket,localport the port number of the local host, LOCALADDR, and BINDADDR is the address of the local machine (the ServerSocket host address), Impl is the parent of the socket, which can be used to create serversocket and to create the socket. Count indicates the maximum number of connections that the server can support. For example:

Socket client = new Socket ("127.0.01", 5555); 127.0.01 represents native IP address at any time, and 5555 is a custom port number

ServerSocket Server = new ServerSocket (5555);

Note that you must be careful when choosing a port. Each port provides a specific service,

Only the correct port is given to obtain the appropriate service.

The 0~1023 port number is reserved for the system, for example, the port number of the HTTP service is the port number for the 80,telnet service is 23 for the 21,FTP service.

So when we select the port number, it's best to choose a number greater than 1023 to prevent conflicts.

If an error occurs when the socket is created, a ioexception is generated and must be processed in the program. So in creating a socket or serversocket you have to catch or throw an exception.

(iv) Simple client/server procedures


Functions implemented by the program:

(1) server in each client login time: Send a message to the client "server is sending you a message." , and then displays the client host address on the connection on the server side.

(2) Client connection, will receive a message, and the server can always send text messages.

(3) The server can always receive the client's SMS.

(4) The server here only write a sentence, but want to be like the client as long as the writing is also possible, change it.

1. Preparation of server-side programs

Package com.xykj.server;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.net.ServerSocket;
Import Java.net.Socket;  /** server-Side inheritance Thread * Enables simple interaction * */public Class Server extends Thread {//define Server interface ServerSocket ServerSocket servers

	= NULL;
		Define a server that defines the port public server (int port) {try {server = new ServerSocket (port);
		catch (IOException e) {e.printstacktrace ();
		The thread that sent the message @Override public void Run () {super.run (); try {System.out.println (server in startup ...)
			Wait for user's connection "); Always receive a user's connection, send a message after the connection to the user while (true) {/Establish Socket interface, accept method is a blocking process, wait until there is a user connection to go down//define socket class socket Socke
				t = server.accept ();
				The output stream can be obtained through the socket object, which is used to write data outputstream OS = Socket.getoutputstream (); Send a message to the client Os.write ("The server is sending you a message.")
				". GetBytes ()); Displays computers on the server that are connected, System.out.println (Socket.getinetaddress (). Gethostaddress () + "connected."
				"); An input stream can be obtained from the socket object to read the user data InputStream Is=socket.getinputStream ();
				reading data int len=0;
				Byte[] Buf=new byte[1024];
				while ((Len=is.read (BUF))!=-1) {//directly print out the obtained data System.out.println ("The server receives the data from the client:" +new String (Buf,0,len));
		A catch (IOException e) {e.printstacktrace ());
 }
	}
}




Startup of the server:

Package com.xykj.server;


public class Servertest {public

	static void Main (string[] args) {//
		
		here the server only needs to define a port number, and the program will automatically obtain the IP address
		/ But the client needs to connect this server, need to know its IP address and port number
		//IP Address view method: Enter CMD window, enter Ipconfig/all can see
		 server server=new Server (6768);
		 Server.start ();
	}




2. Preparation of client programs

Package com.xykj.client;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.net.Socket;
Import java.net.UnknownHostException;

Import Java.util.Scanner;

	public class Client extends Thread {//define a Socket object socket socket = NULL;
		Public Client (String host, int port) {try {//require the IP address and port number of the server to get the correct socket object socket = new socket (host, port);
		catch (Unknownhostexception e) {e.printstacktrace ();
		catch (IOException e) {e.printstacktrace ();
		} @Override public void Run () {//client one connection can write data server new Sendmessthread (). Start ();
		Super.run ();
			try {//Read sock inside the data inputstream s = Socket.getinputstream ();
			byte[] buf = new byte[1024];
			int len = 0;
			while (len = S.read (buf))!=-1) {System.out.println (new String (buf, 0, Len));
		} catch (IOException e) {e.printstacktrace (); }//write data to socket, need to open a new thread class Sendmessthread extends thread{@Override public void Run () {suPer.run ();
			Write Operation Scanner Scanner=null;
			OutputStream os= null;
				try {scanner=new scanner (system.in);
				Os= Socket.getoutputstream ();
				String in= "";
					do {in=scanner.next ();
					Os.write (("Client:" +in). GetBytes ());
				Os.flush ();
			while (!in.equals ("Bye"));
			catch (IOException e) {e.printstacktrace ();
			} scanner.close ();
			try {os.close ();
			catch (IOException e) {e.printstacktrace ();
 }
		}
	}
}




To start the client:

 

Package com.xykj.client2;
public class ClientTest2 {public
	static void Main (string[] args) {
		//requires the correct IP address and port number of the server
		 Client2 client2=new Client2 ("192.168.18.128", 6768);
		 Client2.start ();
	}


In the program to open the server first, in the open client, otherwise it will be an error.

There is a general computer is a dynamic IP address, changing every day. Be aware of the changes.


  


(v) Support for multi-client client/server procedures

In practice, a permanent program is often run on a server that can receive requests from multiple other clients,

Provide the appropriate services. The server always listens for client requests on the specified port, and once the client requests are tapped,

The server starts a dedicated service thread to respond to the customer's request.

And the server itself after the start of the thread and then immediately into the listening state, waiting for the next customer arrival.

And each user corresponds to a fixed thread to receive the information.

The server also sends the received information to all clients on the connection.

Example: Multi-person chat room implementation:


1. Server-side design


Package com.xykj.server2;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import java.util.ArrayList;

Import java.util.List; /** * can be implemented with the client to send messages to each other interaction can be multiple computers */public class Server2 extends Thread {//The value of the socket object used to hold the user on the connection list = new

	Arraylist<> ();

	Define server Interface ServerSocket ServerSocket server = null;
		Define a server that defines the port public Server2 (int port) {try {server = new ServerSocket (port);
		catch (IOException e) {e.printstacktrace ();
		The thread that sent the message @Override public void Run () {super.run (); try {while (true) {//socket interface, accept method is a blocking process, wait until there is a user connection to go down//define the Socket class socket socket = Server.accept (
				);
				The computer on which the server displays the connection, String message = Socket.getinetaddress (). Gethostaddress (). toString ();
				System.out.println (message+ "Connected");
				Send a message to the user Sendmessagetoalluser.
				Add the user on the connection to the collection; inside to list.add (socket); Start the thread of the newly connected user,Used to read the data new Readerthread (socket) all the time. Start ();;
		} catch (IOException e) {e.printstacktrace (); 
		}//Send the message to each user, involving the operation of the write OutStream private void Sendmessagetoalluser (String message) {//Get each user's socket object and write data to it
					for (socket socket:list) {//The saved connection is still in the IF (socket!= null && socket.isconnected ()) {try {
					OutputStream OS = Socket.getoutputstream ();
					Os.write (Message.getbytes ());
				Os.flush ();//Refresh the written data, it is necessary to catch (IOException e) {e.printstacktrace ();

		Read the client's information class Readerthread extends Thread {InputStream is = null; A socket object is passed in here because each user has to read the data public readerthread (socket socket) {try {//Get input stream I
			s = Socket.getinputstream ();
			catch (IOException e) {e.printstacktrace ();
			@Override public void Run () {super.run ();
				try {int len = 0;
				byte[] buf = new byte[1024]; while (len = Is.read (buf))!=-1) {//Read toThe data is sent to other users Sendmessagetoalluser (new String (buf, 0, Len));
			} catch (IOException e) {e.printstacktrace ();
 }
		}
	}
}




Start the service side:


Package com.xykj.server;
public class Servertest {public
static void Main (string[] args) {//
here the server only needs to define a port number, the IP address program will automatically get
/ But the client needs to connect this server, need to know its IP address and port number
//IP Address view method: Enter CMD window, input ipconfig/all can see
 Server2 server=new Server2 (6768);
 Server.start ();
}
 




2. Client-side design


This and the previous example of the client's design is basically the same, no longer repeat the paste.

Summary: The above is mainly to Java Network Programming socket interface class use,

There is also the application of the TCP protocol (the main application of the socket),

Of course TCP also has a more important application is file transfer,

It involves more complex string processing (both before and after receiving),

If you are interested, you can design it yourself.

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.