Java note 24. TCP network programming, java. tcp network programming

Source: Internet
Author: User

Java note 24. TCP network programming, java. tcp network programming
TCP network programmingReprinted please indicate the source: http://blog.csdn.net/u012637501 (embedded _ small J of the sky) from the above section content can know that the use of UDP communication between the two programs is equal, no primary and secondary points, the two program codes can be exactly the same. However, the two applications that use the TCP protocol for communication have the master-slave relationship. One is called a server program and the other is called a client program. The ServerSocket class is provided in Java to create the socket on the server, and the Socket class is used to create the socket on the client.1. Introduction to APIsJava.net. ServerSocket(1) function: used to create a server Socket. The server Socket waits for client applications on the network to send connection requests. (2) constructor> ServerSocket ():> ServerSocket (int port)> ServerSocket (int port, int backlog)> ServerSocket (int port, int backlog, InetAddress bindAddr) use the first constructor to create a ServerSocket object. It is not bound to any port number and cannot be used directly. You must call the bind method to complete other constructor functions. Create a ServerSocket object using the second constructor and bind it with the specified port number. If the port is 0, the system will allocate a port number that is not used by other network programs. As a server program, the port number must be specified in advance, and other customers can connect according to the port number. Create a ServerSocket object by using the third constructor, bind it to the specified port number, and specify the number of Waiting customers (50 by default) that can be connected to the server when the server is busy according to the backlog parameter ). Create a ServerSocket object using the third constructor, bind it to the specified port number, specify the number of Waiting customers, and specify the local IP address. (3) Common method Socket accept (): the server waits for the client to send a connection request and returns the Socketvoid bind (SocketAddress endpoint) of the server ): bind the server Socket to the specified address (IP address and port number) void close (): close the SocketInetAddress getInetAddress (): return the local address (IP address and port number) of the server socket) int getLocalPort (): returns the local port number of the socket on the server.Java.net. Socket(1) function: to establish a connection between the client and the server, you must first create a Socket object. (2) constructor> Socket ()> Socket (String host, int port)
> Socket (InetAddress address, int port)> Socket (InetAddress address, int port, InetAddress localAddr, int localPort)> Socket (String host, int port, InetAddress localAddr, int localPort) the first constructor is used to create a Socket object, which is not connected to any server and cannot be used directly. You need to call the connect method. Create a Socket object using the second or third constructor and establish a connection with the server program of the specified IP address and port number. Here, String host is the String format address, and InetAddress address is the address encapsulated by the InetAddress object. Create a Socket object using the fourth or fifth constructor, establish a connection with the server program of the specified IP address and port number, and specify the local IP address and port number bound to the local Socket (client. (3) Common method> void connect (SocketAddress endpoint): connect the client socket to the specified server> void connect (SocketAddress endpoint, int timeout ): connect the client socket to the specified server and specify the time limit> void close (): close the client socket> InetAddress getInetAddress (): return the server program IP address> int getPort (): return the port number of the server program> InputStream getInputStream (): return an input stream of the client socket> OutputStream getOutputStream (): return an output stream of the client socket
Ii. Server-Client model of TCP protocol1. Establish the Server-Client Model(1) The server program creates a ServerSocket and calls the accept method to wait for the client to connect. (2) The client program creates a Socket and requests a connection with the server. (3) the server receives a connection request from the customer and creates a new Socket (belonging to the server) to establish a leased line connection with the customer. (4) the two sockets that have just established a connection talk on a separate thread (created by a server program); (4) the server starts to wait for a new connection request. The server program calls ServerSocket. the accept method (return the Socket of the server) waits for the client's connection request. Once the accept receives the client's connection request, the method returns a Socket object that has established a leased line connection with the customer, instead of creating this server Socket object. When two sockets on the client and server establish a leased line connection, one end of the connection can write bytes to the other end consecutively and read bytes from the other end consecutively, that is, the two sockets with leased line connections exchange data in the form of IO streams. Java provides the Socket. getInputStream method to return the input stream object of the Socket, and the Socket. getOutputStream method to return the output stream object of the Socket. As long as a connection segment writes data to the output stream object, the other end of the connection can read the data from its input stream object.
Iii. Source Code practice1. The simplest TCP server programImplementation: Develop a simple TCP server application, set its port number, and use the telnet tool in Windows to communicate with the client. ServerTCP. java

<Span style = "font-size: 18px;"> import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java.net. serverSocket; import java.net. socket; public class ServerClient {public static void main (String [] args) {try {// 1. create a ServerSocket object to return the Socket of the server and specify the server port number ServerSocket server = new ServerSocket (8000); Socke T socket = server. accept (); // 2. obtain the input/output stream InputStream is = Socket of the leased line socket. getInputStream (); OutputStream OS = socket. getOutputStream (); // 3. write byte data to the output stream String str = "My name is jiangdongguo. how are you! "; OS. write (str. getBytes (); // 4. bufferedReader br = new BufferedReader (new InputStreamReader (is); System. out. println (br. readLine (); // byte [] buf = new byte [1024]; // int len = is. read (buf); // System. out. println (new String (buf, 0, len); // print the actual data socket. close (); is. close (); OS. close (); server. close ();} catch (IOException e) {e. printStackTrace () ;}}</span>
Source code analysis(1) ServerSocket server = new ServerSocket (8000); the statement creates a ServerSocket object waiting for connection on port 8000 for the server program. After receiving a connection request from a customer, the program obtains the input and output stream object from the Socket object connected to this customer. The output stream first sends a string of characters to the client, and then reads the information sent by the customer through the input stream, store the information in a byte array and close all related resources. (2) The telnet Tool sends the message if it has input, rather than press Enter. If the server outputs the received data in the format of one row. Java provides a BufferedReader class to process input streams by row. Effect demonstration:
The following results show that the server first writes data to the output stream of the Socket. After Telnet is successfully connected to the developed server, Telent reads data from the socket input stream as the client and displays the data on the terminal. In addition, after the command terminal of our (telnet) Client writes data to the socket output stream, the server program will read the socket input stream and print it to the Eclipse terminal.
2. Server_Client Model Application Development (1) server sideFunction: based on the previous program, the server program can receive connection requests from multiple clients and create a separate thread for each client connection to communicate with the customer.> ServiceThread. java sub-thread function code. Data exchange for each connection needs to be placed in a loop statement to ensure that the two can exchange data continuously. Each time the client sends a string to the server, the server sorts all the characters in the string in reverse order and sends them back to the client until the client sends the quit command to the server to end the conversation between the two ends.
<Span style = "font-size: 18px;"> import java. io. bufferedReader; import java. io. dataOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java.net. socket; // implement the Runnable interface subclass to complete the sub-thread task public class ServiceThread implements Runnable {Socket socket;/* constructor to pass a Socket object parameter */public ServiceThread (Socket socket) {this. socket = socket;}/* member Method */public void run () {try {/* retry * // 1. obtains the input stream and output stream object InputStream of the Socket. getInputStream (); OutputStream OS = socket. getOutputStream (); // 2. create two packaging classes for the input stream and output stream: BufferedReader br = new BufferedReader (new InputStreamReader (is); // input stream packaging class DataOutputStream dos = new DataOutputStream (OS ); // output stream packaging class/* packages * // 3. this thread keeps reading the data in the input stream and reverse the while (true) {String str = br. readLine (); // read a line of string if (str. required signorecase ("quit") break; String strReverse = (new StringBuffer (str ). reverse (). toString (); // returns the dos string in reverse order. writeBytes (str + "------>" + strReverse + System. getProperty ("line. separator "); // write byte data to the output stream} br. close (); dos. close (); socket. close ();} catch (IOException e) {e. printStackTrace () ;}}</span>
Source code analysis: (1) BufferedReader and DataOutputStream classes: These two classes are IO packages. The BufferedRead class can easily read a string from the underlying byte input stream in the form of a whole line; the DataOutputStream class can write a string to the underlying byte output stream in the form of a byte array. (2) System. getProperty ("line. separator") is used to return line breaks based on different operating systems. (3) when creating a server program Socket, you must specify the port number (the client can know which network program is the server). Then, you can obtain the input stream and output stream of the Socket for data interaction with the client. Thread ------------------------> TCPServer. java main thread. Only one connection is accepted for an accept method call at a time. The accept method must be executed in a loop statement to receive connections from multiple clients.
<Span style = "font-size: 18px;"> import java. io. IOException; import java.net. serverSocket; import java.net. socket; public class TCPServer {public static void main (String [] args) {try {ServerSocket ss = new ServerSocket (8010); // instantiate a ServerSocket object while (true) {Socket socket = ss. accept (); // wait for the client connection request. After the request succeeds, the system returns the socket new Thread (new ServiceThread (socket) of the server )). start (); // when the connection is successful, create a thread for socket communication and start the thread} catch (IOException e) {e. printStackTrace () ;}}</span>
(2) Client> TCPClient. java
<Span style = "font-size: 18px;"> import java. io. bufferedReader; import java. io. dataOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java.net. inetAddress; import java.net. socket; public class TCPClient {public static void main (String [] args) {try {// 1. create a client socket and specify the Server IP address and port number Socket socket = new Socket (InetAddress. getByName ("192.168.1.100"), 8010); // 2. obtain the input stream and output stream of the socket. InputStream is = socket. getInputStream (); OutputStream OS = socket. getOutputStream (); // 3. instantiate two packaging classes BufferedReader br = new BufferedReader (new InputStreamReader (System. in); DataOutputStream dos = new DataOutputStream (OS); BufferedReader bri = new BufferedReader (new InputStreamReader (is); while (true) {String strKey = br. readLine (); // read a row of dos data from the input stream. writeBytes (strKey + System. getProperty ("line. separator "); // write the keyboard data to the output stream if (strKey. endsWith ("quit") // when you enter quit, disconnect break; else System. out. println (bri. readLine (); // read a row of data from the input stream and print} socket. close (); br. close (); dos. close (); bri. close ();} catch (IOException e) {e. printStackTrace () ;}}</span>

Source code analysis(1) Socket socket = new Socket (InetAddress. getByName ("192.168.1.100"), 8010); the statement is used to create a client Socket and specify the Server IP address and port number. However, to make our applications more flexible, you can enter the Server IP address and port number through the command terminal: Socket socket = null; if (args. length <2) // specify the Default Server IP address and port number {socket = new Socket (InetAddress. getByName ("192.168.1.100"), 8010);} else // specify {socket = Socket (InetAddress. getByName (args [0]), Integer. parseInt (args [1]);} Note: The above method is consistent with the idea of setting the port on the server.
Result 1:Telnet is used as the client. Observe the following results and we can see that after running multiple "Telnet Server IP server port numbers" on the command line, the Client Program establishes a connection with the server in a separate thread to implement data exchange.
DEMO 2:Here we use the prepared application as the client. Each customer can talk to the server separately until the customer enters the quit command and ends. The effect is the same as that of telnet.

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.