In the previous blog, we simply sorted out the process of JAVA creating server and client connecting server. Today, we continue to learn to realize the communication between client and server. Since the basic concepts have been clarified in the previous blog post, we will not repeat them here. (For those who are not clear, read my previous blog below.)
Specific code
package communicatetest1; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; //Create a test class public class communicateTest { public static void main(String[] args) throws IOException { //Create a server object ServerSocket server=new ServerSocket(9005); //Output server port information System.out.println("The server was successfully created with a port number of:"+server.getLocalPort()); while(true) { //Create a Socket object to connect. There is no need to create a new object here. It just refers directly to the server. Socket socket=server.accept(); //Using socket to receive data of output input stream //One thing to note here is that OutputStream outputs information to the client, while InputStream reads information sent by the client. OutputStream output=socket.getOutputStream(); InputStream input=socket.getInputStream(); //Then start the communication test. String s="Hello,Welcome to My ServerSocket!"; //This message is a message sent by the server to the client when the client connects to the server we created. //That is to say, we want to send messages to the client, so we should use OutputStream. //First, we need to convert the sending information into byte type, because the parameter in the write() method of the output stream is byte type. byte[] dataout=s.getBytes(); //Then call the write method of the output stream and send the information to the client. output.write(dataout); //Then let this information be displayed on the command line so that we can check if the information has actually been sent. output.flush(); //Receive each character from the client int ascii=input.read(); //End the loop if a carriage return character is received while(ascii!=13) { char accept=(char) ascii; //Output every character sent by the client and received by the server System.out.print(accept); ascii=input.read(); } //Close connection socket.close(); } } }
We added a piece of code to the previous blog code. The read() method of InputStream is used to transmit information to the server. It should be noted that the ascii code of the character is obtained by the read() method, so we need to receive the variable of int and convert it into char character.
2. Run the command line as follows
After entering telnet localhost 9006, connect as follows
When we try to enter some characters, we will see the following interface
Each time a character is entered on the command line, the server receives a character. Instead of writing a sentence we imagined, press Enter before sending it to the server. But this form of sending is not very suitable for our daily life. And it can't be deleted. Because every time we write a character, it is sent to the server immediately. When you press the delete key, it will be recognized as a character sent to the server.
3. Setting Read and Send Rules
If we want to achieve the normal communication between client and server, we must set certain reading rules for them, instead of reading character by character. For example, we can specify that the return key is the end of a complete message. Each time the return key is read, the server receives the message once more. As functionality grows, we'd better encapsulate it as a class instead of always testing it in the main function. The code was modified as follows:
package communicatetest2; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; //Define a communication class public class ServerChat { OutputStream output;//output stream InputStream input;//Input stream ServerSocket server;//Setting a server object property //Define a way to build a server private void setUpServer(int port) throws IOException { //Set the input port to the server server=new ServerSocket(port); //Output the port number of the current server System.out.println("The server was successfully created with port number:"+server.getLocalPort()); //Define a Socket as a Mediator Receiving Object Socket socket=server.accept(); //Assigning values to input and output streams output=socket.getOutputStream(); input=socket.getInputStream(); //Start communication //Delivery of information to clients String outS="Hello,welcome to my ServerSocket!\r\n"; out(outS); //Send information to server ReadString(); } //Define a way to output information to the client private void out(String outS) throws IOException { //Converting strings to byte arrays byte[] dataout=outS.getBytes(); //Call write() to send information to the client output.write(dataout); //Force output to the command line interface output.flush(); } //Define a way to send strings to the server public void ReadString() throws IOException { String inputS=""; //Read the first character int AsciiNumber=input.read(); while(AsciiNumber!=13) { //Converting ascii codes to corresponding char characters inputS+=(char)AsciiNumber; //Receive the next character AsciiNumber=input.read(); } System.out.println(inputS); output.close(); } //Main function entry public static void main(String[] args) throws IOException { //Create an object of a communication class ServerChat server=new ServerChat(); server.setUpServer(9009); } }
The command line runs as follows
In this way, we can get back to the car and then show it. But in essence, he is still a character-by-character transmission, but when the server receives the character, we do not immediately display it, but wait to accept the complete sentence, we will display it. But now it has another problem, that is, it can only transmit a word, which is very difficult. Who can only say one word, so we need to improve it. When we finish receiving a sentence, don't close the connection between the client and the server immediately, but wait until the user enters "bye" before disconnecting. The code of the relevant section is changed as follows:
public void ReadString() throws IOException { String inputS=""; while(!inputS.equals("bye")) { //Read the first character int AsciiNumber=input.read(); while(AsciiNumber!=13) { //Converting ascii codes to corresponding char characters inputS+=(char)AsciiNumber; //Receive the next character AsciiNumber=input.read(); } System.out.println(inputS); } //Close connection output.close(); }
Running the command line results as follows
Now we can exchange many pieces of information.~
Now, of course, we only allow the server to communicate with one client. When one client communicates with the server, if the second client tries to connect with the server, the following error will occur.
The reason is simple. At present, we are only a single thread program. When a client communicates with a server, the thread is already occupied. Later, I will continue to launch a blog to explain the implementation of JAVA multi-threaded communication and support multi-person chat.