Socket programming in Java

Source: Internet
Author: User

Socket programming in Java

Xu yingxiao (Shanghai University Computing Center 25 #) xyx@yc.shu.edu.cn

Abstract: This article introduces socket programming in Java, including programming methods on the server and client, and provides several examples.

Key words: Java, socket, server, client, Internet

1. What is socket?

The socket interface is the most widely used method to access the Internet. If you have a host with the TCP/IP protocol, its IP address is 202.120.127.201. At this time, you can execute FTP 202.120.127.201 on another host or the same host. Obviously, you cannot establish a connection. Because "202.120.127.201"

This host does not run the FTP service software. Similarly, if you run a browser software such as Netscape on another or the same host and enter "http: // 202.120.127.201", the connection cannot be established. Now, if you run an FTP service software on this host (the software opens a socket and binds it to port 21 ), then run a web service software on the host (the software will open another socket and bind it to port 80 ). In this way, FTP 202.120.127.201 will be executed on another host or the same host. The FTP client software will call the socket provided by the FTP service software on the host through port 21, establish a connection with and talk to it. When "http: // 202.120.127.201" is entered in Netscape, the socket provided by web service software on the host is called through port 80 to establish a connection with and talk to it.

There are many such hosts on the Internet. These Hosts generally run multiple service software and provide several services at the same time. Each service opens a socket and binds it to a port. Different ports correspond to different services. Socket is like a porous socket, just as it was originally intended. A host is like a room with various sockets. Each socket has a serial number. Some sockets provide 220 v ac, some provide 110 v ac, and some provide cable TV programs. The customer software inserts the plug into a socket with different numbers to obtain different services.

The corresponding socket programming method is provided in Java. You can use Java to write both the server-side program and the client-side program.

2. Compile the server program

The serversocket class in Java provides the socket interface of the server. To enable everyone to have a perceptual knowledge of writing server programs, we provide a service software simulating FTP servers. For the sake of conciseness, this program only provides the simplest FTP connection function.

The program 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 program, you can run it on a computer with Windows 95 installed and configured with TCP/IP protocol (not necessarily connected to the Internet ). Install Java compilation software such as jdk1.01 or jdk1.02 on the microcomputer (which can be downloaded in the ftp://ftp.javasoft.com/pub/JDK-102-win32-x86.exe) and save the above program to the file ftpserver. java, Run "javac ftpserver. java "to compile it into a bytecode file ftpserver. class. In this way, as long as "Java ftpserver. Class" is executed on the microcomputer to run the Java program, the microcomputer becomes a simulated FTP server.

The simulated FTP server can be tested on another networked microcomputer, or a DOS window can be opened directly on the simulated FTP server. Run the FTP client software in the command line format. For example, run FTP 202.120.127.201 in the DOS window of Windows 95 (if the IP address used When configuring the TCP/IP protocol in Windows 95 is another value, you can change "202.120.127.201" to the corresponding value. Is the dialog process. The underlined part is the user 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

Simulate FTP Server

C:/xyx/Java/sock/bak/ftp> JAVA ftpserver

Got follow infor from client: USER anonymous

Got follow infor from client: Pass xyx@yc.shu.edu.cn

Got follow infor from client: Quit

Let's take a look at the programming method of the simulated FTP server. In the above program, the key part is the following four sentences:

1. serversocket ftpserver = new serversocket (21 );

2. Socket FS = ftpserver. Accept ();

3. printstream fs_out = new printstream (FS. getoutputstream ());

4. datainputstream fs_in = new datainputstream (FS. getinputstream ());

In the first sentence, a server socket is created and bound to port 21. In this way, the socket on the server will always wait for the client to establish a connection. Port 21 is the usual port for the FTP service. You can also use other ports to provide your own services. The second sentence is to use the method accept () provided by Java to receive client connections. The third and fourth sentences open an output and input stream for the established connections respectively. These four sentences can be used as a paradigm for writing server programs. The next operation is to read and write the output and input streams according to the agreed protocol.

In the above program, use the println ("... ") Send a string to the client, get the string sent by the client to the server from the input stream fs_in using Readline (), and use system. out. println ("... ") displayed on the server.

Sending information to the client and reading the information sent from the client must be performed in accordance with the Protocol so that the communication between the server and the client can be smooth. In the above program, the message sending order is as follows:

1. After the client is connected, the server sends a welcome message to the client. This is done by the following line in the program:

Fs_out.println ("welcome to the test server ");

2. The client displays the information sent by the server and prompts the user to enter an 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, sends the result code 331 to the client, and prompts that a password is required. This is done by the following two lines in the program ::

System. Out. println ("got follow infor from client:" + fs_in.readline ());

Fs_out.println ("331 please send password ");

4. The client prompts the user to enter the password and sends it to the server. In this example, this is done by the FTP client software.

5. The server receives the password provided by the client, sends the result code 230 to the client, and prompts that the registration is successful. Read the client sending command. This is done by the following two lines in the program:

Fs_out.println ("230 login OK ");

System. Out. println ("got follow infor from client:" + fs_in.readline ());

From the above, we can see the simple process of the client-server conversation. Here, we omit the server's test of the user and password and perform various operations according to the different commands entered by the client. In fact, in the above example, we can see how the server sends information to the client and how the server receives the client information. Therefore, as long as you understand the agreement of the two sides, it is not difficult to make appropriate programming.

3. Compile the client program

In the above program, we borrowed the FTP client software provided by Windows 95 to test our simulation FTP service program. Now, we need to write a client program. We first compile a simple server program and client program to understand the communication between the server and the client and its programming.

For the sake of conciseness, we use a simple protocol defined by ourselves: the server uses an idle port 8886, after the client connection: 1. the server sends a message to the client. 2. the client reads and displays the server information and sends a feedback to the server. 3. the server reads and displays the feedback from the client.

Corresponding to this Protocol, the server program 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 client:" + S1 );

}

Catch (exception E)

{System. Out. println (E );

}

}

}

This example is similar to the preceding simulated FTP server. The difference is that the service provider uses port 8886. In addition, the input and output streams are operated differently due to different protocols. 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 );

In the first sentence, a client socket is created to establish a connection with the host 202.120.127.201. 8886 indicates the port number, which corresponds to the port number bound to the socket on the server. The second to fourth sentences create input and output streams for the socket. These four statements can be used as a paradigm for compiling client programs. The next operation is to operate the output and input streams according to the agreed protocol. In the previous program, the method Readline () is also used to read the string sent by the server for the input stream client_in, and the method println ("...") for the output stream client_out is used to send the string to the server.

The above two programs are compiled and executed 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 client: This is infor sent by Client

During the test, Two Dos windows can be opened on the same microcomputer or two networked computers. Based on the above program, we can compile a client program for the preceding simulated 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, usertyped;

While (fromserver = client_in.readline ())! = NULL ){

System. Out. println ("server:" + fromserver );

While (C = system. In. Read ())! = '/N '){

Buf. append (char) C );

}

Usertyped = Buf. tostring ();

Client_out.println (usertyped );

Client_out.flush ();

Buf. setlength (0 );

}

} Catch (exception e ){

System. Out. println (E );

}

}

}

The program is similar to the previous program. The difference is that the program uses a loop:

While (fromserver = client_in.readline ())! = NULL ){

...}

Read the input from the server repeatedly and use:

While (C = system. In. Read ())! = '/N '){

Buf. append (char) C );

}

Usertyped = Buf. tostring ();

Client_out.println (usertyped );

The statement reads the user's keyboard input and sends it to the server. The dialog 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 client: xyx@yc.shu.edu.cn

Got follow infor from client: Bye

It is worth mentioning that the customer software can not only communicate with the preceding analog FTP server, but also communicate with the real FTP server. If you change the IP address "202.120.127.201" in the customer's software to the IP address of an 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, and quit are the user accounts, passwords, and Exit commands specified in the agreement.

4. Process client requests

The preceding example only transmits information between the server and the client. In practice, the server should be able to make different responses to different client inputs. This section provides an example for the server to process client requests. The Protocol is as follows: after the client connects, the server sends "Welcome to time server" information, and the client reads user input and sends it to the server, if the client input is hours, the current number of hours is sent to the client. If the client input is minutes, years, month, day, time, date, or down, send the Minutes, years, months, dates, hours, minutes, and days to the client, and end the session when the client enters down.

The client still uses the client program that simulates the FTP server written in the previous section, but the port 21 in the program needs to be changed to 8885, so as to talk to the following server program. The program modification on the server is 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 ");

Server_out.flush ();

Date T = new date ();

While (inputline = server_in.readline ())! = NULL ){

System. Out. println ("got" + inputline );

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 is:" + hours );

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 (inputline. equalsignorecase ("month "))

Server_out.println ("current month is:" + month );

Else if (inputline. equalsignorecase ("day "))

Server_out.println ("current day is:" + Day );

Else if (inputline. equalsignorecase ("time "))

Server_out.println ("current times is:" + hours + ":" + minutes + ":" + seconds );

Else if (inputline. equalsignorecase ("date "))

Server_out.println ("current date is:" + years + "." + month + "." + Day );

Else server_out.println ("I don't know ");

Server_out.flush ();

}

}

Catch (exception e ){

System. Out. println (E );

}

}

}

In this program, use a method similar to the previous client, with a loop

While (inputline = server_in.readline ())! = NULL ){

...}

Read client information repeatedly. In the loop, different processing is performed based on different information sent from the client.

5. Program Optimization

To optimize the program, you can start from the following aspects:

1. handle errors

If you can use try {...} for each sentence {...} catch (...) {...} handle exceptions in the program, Return Error information or handle errors properly.

2. Disable open socket and stream

When the conversation ends, the opened socket and stream are closed. The severscoket, socket, datainputstream, and dataoutputstream classes in Java provide the method close () to implement this function.

3. Support multiple connections

The previous server program will automatically end after a conversation is completed. If a client wants to establish a connection, the server program needs to be re-executed. To enable the server to support multiple connections, you only need to use one loop. For example, for all the preceding server programs, you can include the first line of the "accept ()" Statement to the "} catch (exception E)" statement in while (true) {...} so that it supports multiple connections.

4. Use threads

Server programs generally use threads to handle other tasks while waiting for client connection. In addition, by allocating a new thread to each client request, the server can support multiple connections at the same time to process client requests in parallel.

[References 〗

1. Mary Campione and Kathy walrath,

"The Java tutorial ",

Last Updated 4 Mar 96.

Ftp://ftp.javasoft.com/docs/tutorial.html.zip

2. Laura Lemay,

Charles L. Perkins,

"Teach Yourself Java in 21 days"

3. "the Java language tutorial"

Ftp://java.sun.com/docs/progGuide.html.zip

4. elharo@sunsite.unc.edu,

"Brewing Java: a tutorial ",

Last-modified: 1996/9/20,

Http://sunsite.unc.edu/javafaq/javatutorial.html

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.