Socket programming in Java language

zhaozj2021-02-16  73

Java language Socket programming Xu Yingxia (Shanghai University Calculation Center 25 #) xyx@yc.shu.edu.cn Abstract: This article introduces the Socket programming of the Java language, including the server and client programming methods, and provides several instances. Keywords: Java, Socket, Server, Client, and Internet Interface is the most widely used method for accessing the Internet. If you have a host that just matches the TCP / IP protocol, its IP address is 202.120.127.201. At this point, FTP 202.120.127.201 is executed on another host or the same host, obviously unable to establish a connection. Because "202.120.127.201" This host does not run FTP service software. Similarly, running browsing software such as Netscape on another or the same host, enter "http://202.120.127.201", and connection cannot be established. Now, if you run an FTP service software on this host (this software will open a socket, then bind it to the 21-port), then run a web service software on this host (this software will open another socket And bind them to 80 ports). In this way, the FTP 202.120.127.201 is performed on another host or the same host, and the FTP client software will call the host by the 21-port to call the Socket provided by the FTP service software, and establish a connection and conversation with it. When "http://202.120.127.201" is entered in Netscape, the SOCKET provided by the Web Services software will be used via the 80-port, and the connection is established and conversible with it. There are many such hosts on the Internet, which typically run multiple service software while providing several services. Each service opens an Socket and binds to a port, and the different ports correspond to different services. Socket is like a porous socket as its English is. A host is like a room full of various sockets, each outlet has a number, some outlets provide 220 volts, and some provide 110 volts, and some provide cable TV programs. The client software plugs the plug to different numbered sockets, you can get different services. In the Java language, the corresponding Socket programming method is provided. Use Java to write server programs and write client programs. Second, the ServerSocket class in Java in writing the server provides the server's Socket interface. In order to make everyone have an inductive understanding of the written server program, it provides a service software for an analog FTP server. For the sake of simplicity, the program only provides the easiest function of establishing an FTP connection.

The procedure is as follows: import java.io. *; import java.net. *; Public class ftpserver {public static void main (string args []) {Try {serversocket ftpserver = new serversocket (21); socket fs = ftpserver.accept (); PrintStream fs_out = new PrintStream (fs.getOutputStream ()); DataInputStream fs_in = new DataInputStream (fs.getInputStream ()); fs_out.println ( "Welcome to the test server"); System.out.println ( "got FOLLOW Infor From Client: " fs_in.readline ()); fs_out.println (" 331 please send password "); system.out.println (" Got Follow Infor From Client: fs_in.readline ()); fs_out. Println ("230 login ok"); system.out.println ("Got Follow Infor From Client: FS_IN.Readline ());} catch (exception e) {system.out.println (e);}}} To test the procedure, it can be performed on a microcomputer installed on the Windows 95 and configured with the TCP / IP protocol (not necessarily a connection to the Internet). Install Java compilation software on this microcomputer such as JDK1.01 or JDK1.02 (can be downloaded in ftp://ftp.javasoft.com/pub/jdk-102-win32-x86.exe), save the above program into file FTPServer .java, execute "javac ftpserver.java" to compile it as byte code file ftpserver.class. Thus, "Java ftpserver.class" is executed on the microcomputer to run the Java program, the microcomputer becomes an analog FTP server. Test the analog FTP server, can be performed on the other networked microcomputer or on the analog FTP server to open another DOS window. Run the FTP client software in the form of command line, such as performing: FTP 202.120.127.201 (if you configure the TCP / IP protocol in your Windows 95, you need "202.120 here). 127.201 "Change to the corresponding value), you can perform a conversation. The following figure is the dialog process, where the underlined portion is the user's input.

Client C: / XYX / JAVA / SOCK / BAK / FTP> FTP 202.120.127.201 Connected to 202.120.127.201. Welcome to the test server user (202.120.127.201: (NONE): Anonymous 331 please send password password: xyx @ Yc.shu.edu.cn 230 login OK FTP> BYE Simulation FTP Server C: / XYX / Java / Sock / Bak / FTP> Java FTPServer Got Follow Infor From Client: User Anonymous Got Follow Infor From Clom Client: Pass XYX @ YC. Shu.edu.cn Got Follow Infor From Client: Quit Let's take a look at the programming method of the analog FTP server. In the above program, the key portion is the following four sentences: 1. Serversocket ftpserver = new serversocket (21); 2. Socket fs = ftpserver.accept (); 3. PrintStream Fs_out = new printstream (fs.getStream (); 4. DataInputStream FS_IN = New DataInputStream (fs.getinputStream ()); where the first sentence creates a server's socket and bound it to the 21 port. In this way, the server's socket will wait for the client to establish a connection. The 21-port here is a port-used for FTP services, you can also use other ports to provide their own services. The second sentence uses the method Accept () to receive the client's connection with Java. The third sentence and the fourth sentence open an output and input stream for the connection established, respectively. These four sentences can be used as a paradigm written in the server program, and the next operation is to read and write the output and input streams in accordance with the agreed protocol. In the above program, the output stream FS_OUT is transmitted to the client to send a string to the client, and the input stream FS_IN is used to obtain the character string sent to the server with the system .Tem. Out.println ("...") is displayed on the server. The information sent to the client to read the client to read the client must be made in accordance with the protocol, so that the server and the client can communicate smoothly. In the above program, the information transmission order is such: 1. After the client is connected, the server sends the welcome information to the client. This is done by the following row: fs_out.println ("Welcome to the Test Server"); 2. The client displays the information sent by the server and prompts the user to enter the account and send it to the server. In this example, this is done by the FTP client software. 3. The server receives the account provided by the client and sends the result code 331 to the client, and prompts the password. This is completed by the following two lines :: system.out.println ("Got Follow Infor From Clom Client: FS_IN.READLINE ()); FS_OUT.PRINTLN (" 331 please send password "); 4. Client prompt user Enter the password and send the password to the server. In this example, this is done by the FTP client software. 5. The server receives the password provided by the client and sends a result code 230 to the client and prompts to successfully register. Read the client sends a command.

This is completed by the following two lines: fs_out.println ("230 login ok"); system.out.println ("Got Follow Infor From Clom Cliant: FS_IN.Readline ()); From the above we can see the client And the simple process of the server dialog, where we omitted the server's inspection of the user and password and performs various operations according to the different commands entered by the client. In fact, in the above example, you can see how the server sends information to the client, but also see how the server receives the client's information. Therefore, as long as you understand the agreement between the two parties, it is not difficult to make a corresponding programming. Third, write the client's program in the above program, we borrowed the FTP client software provided by Windows 95 itself to test our analog FTP service programs. Now, we have to write a client's program. We first write a simple server program and client program to understand the communication and its programming of the server and its client. For the sake of concise, we use a simple protocol that you define: the server uses an idle port 8886, the client is connected to: 1. The server sends a message to the client; 2. The client reads the information of the server and display, and then Send a feedback information to the server; 3. The server reads the feedback information of the client and displays. Corresponding to this protocol, the server can be as follows: import java.io. *; import java.net. *; Public class server {public static void main (string args []) {Try {server socket server_1 = new server socket 8886); Socket socket_s = server_1.accept (); Print Stream server_out = new Print Stream (socket_s.get Output Stream ()); Data Input Stream server_in = new Data Input Stream (. socket_s getInputStream ()); server_out.println ( "This is infor Sent By Server / R"); string s1 = server_in.readline (); system.out.println ("Got Follow Infor From Clom Cliant: S1);} catch (exception e) {system.out. Println (E);}}} This example is similar to the previous analog FTP server, and the different is only the 8886 port used by the service provider, and since the protocol used is different, the operation of the input and output stream is different.

The corresponding client program can be as follows: import java.io. *; import java.net. *; Public class client {public static void main (string args []) {Try {socket sock_1 = new socket ("202.120.127.201" , 8886); DataInputStream client_in = new DataInputStream (sock_1.getInputStream ()); DataOutputStream cl_out = new DataOutputStream (sock_1.getOutputStream ()); PrintStream client_out = new PrintStream (cl_out); String s1 = client_in.readLine (); System. Out.println ("Got Follow Infor From Server: S1); Client_Out.println (" this is infor Sent By Client / R);} catch (exception e) {system.out.println (e);}} } This is an example of a simple client program. The key part is the following four sentences: 1. Socket Sock_1 = New Socket ("202.120.127.201", 8886); 2. DataInputStream Client_in = New DataInputStream (sock_1.getinputstream () ); 3. DataOutputStream cl_out = new DataOutputStream (sock_1.getOutputStream ()); 4. PrintStream client_out = new PrintStream (cl_out); wherein a first one to create the Socket client, so as to establish a connection to the host 202.120.127.201. The 8886 is the port number, corresponds to the port number bound to the server's socket. The second to four sentences create input and output streams for Socket. These four sentences can be used as a paradigm written by the client program. The next operation is also the same as the output and input streams in accordance with the agreed protocol. In the last program, the input stream client_in is read using the string sent by the server, and the output stream client_out is transmitted to the server to send a string to the server. The above two programs are compiled after the effects are as follows: Client C: / XYX / Java / Sock / Bak / C-Both-S> Java Client Got Follow Infor From Server: this is infor Sent by Server server C: / XYX / Java / Sock / Bak / C-Both-S> Java Server Got Follow Infor From Clom Clism: This is INFOR SENT BY Client Testing can only open two DOS windows on the same microcomputer, or on the two networking microcomputers get on.

On the basis of the above program, we can write a client program for the previous analog FTP service program: import java.io. *; import java.net. *; Public class ftpc {public static void main (String [] args {try {Socket sock_1 = new Socket ( "202.120.127.201", 21); DataInputStream client_in = new DataInputStream (sock_1.getInputStream ()); DataOutputStream cl_out = new DataOutputStream (sock_1.getOutputStream ()); PrintStream client_out = new PrintStream ( Cl_out); StringBuffer BUF = New StringBuffer (50); INT C; String fromServer, useertyped; while ((fromserver = client_in.readline ())! = null) {system.out.println ("Server:" fromserver); While (c = system.in.read ())! = '/ n') {buf.append ((char) c);} usepeped = buf.tostring (); client_out.println (useertyped); Client_Out.Flush (); buf.setlength (0);}} catch (exception e) {system.out.println (e);}}} This program is similar to the previous program, and the program is in the program uses a loop: while FromServer = client_in.readline ())! = null) {...} Repeatedly read the input of the server, and use: while ((c = system.in.read ())! = '/ n') {buf.Append ((char) c); useped = buf.tostring (); client_out.println (usepepe); The statement reads the user's keyboard input to send to the server. Its dialogue is as follows: Client C: / XYX / Java / Sock / Bak / FTP> Java FTPC Server: Welcome To the Test Server Anonymous Server: 331 please send password xyx@yc.shu.edu.cn Server: 230 login OK BYE Server C: / XYX / Java / Sock / Bak / FTP> Java FTPServer Got Follow Infor From Client: Anonymous Got Follow Infor From Clom Cliant: XYX@yc.shu.edu.cn got Follow Infor From Client: BYE is worth a What is mentioned is that the customer software can not only communicate with the previous analog FTP server, but also communicate with the true FTP server.

If the IP address "202.120.127.201" in the customer software is changed to an IP address of a FTP server: "202.120.127.218", you can use the following communication: c: / xyx / java / sock / bak / ftp> javac ftpc Server: 220 Sun1000E-1 FTP Server (UNIX (R) System V Release 4.0) Ready. User Anonymous Server: 331 Guest Login OK, Send Ident As Password. Pass xyx@yc.shu.edu.cn Server: 230 Guest Login OK , Access Restrictions Apply. Quit Server: 221 Goodbye. User, Pass, Quit is the user account, password, and exit command specified by the protocol. 4. Processing the client request or more only transmits information with the client with the client, in the practical, the server should make different responses to the client different input. This section gives an example of a server processing client request. The protocol is as follows: After the client is connected, the server sends "Welcome to Time Server" information, and the client reads the user input to the server if the client is input to Hours. Send current hours to the client; if the client is input to Minutes, Years, Month, Day, Time, Date, Down, send a number of minutes, year, month, date, time division, year and month to the client; The client input DOWN ends the session. Its client still uses a client program written in the previous section, but it is necessary to change port 21 in the program to 8885 to dialogue with the following server program.

The server is modified as follows: import java.net. *; Import java.io. *; import java.util.date; Class Server {public static void main (string args []) {Try {serversocket server_socket = new serversocket (8885 ); Socket client_Socket = server_Socket.accept (); DataInputStream server_in = new DataInputStream (client_Socket.getInputStream ()); PrintStream server_out = new PrintStream (client_Socket.getOutputStream ()); String inputLine, outputLine; server_out.println ( "Welcome to Time "); server_out.flush (); date t = new date (); while ((InputLine = Server_IN.Readline ())! = null) {system.out.println (" got " infutline); string hours = String.Valueof (T.GETHOURS ()); string minutes = String.Valueof (t.getminutes ()); string seconds = string.valueof (t.Getseconds ()); string years = string.valueof (t.Getyear )); String month = String.Valueof (t.GETMONTH ()); string day = string.valueof (T.getDay ()); if (InputLine.Equalsignorecase ("Down") Break; Else IF (InputLine.Equalsignorecase) ("Hours")) Server_out.println ("Current Hours:" HO urs); else if (inputLine.equalsIgnoreCase ( "Minutes")) server_out.println ( "Current Minutes is:" minutes); else if (inputLine.equalsIgnoreCase ( "Years")) server_out.println ( "Current Years is: " Years); Else IF (" Month ")) Server_Out.println (" Current Month IS: Month); Else IF (InputLine.Equalsignorecase ("day") Server_Out.println ("Current Day IS: " day); INPUTLINE.EQUALSINORECASE (" Time ")) Server_Out.println (" Current Times IS: Hours ":" Minutes ":" Seconds);

转载请注明原文地址:https://www.9cbs.com/read-15601.html

New Post(0)