Java to implement IO communication (server article)

Source: Internet
Author: User

Java to implement IO communication (server article)

How to use Java to implement our communications? First we understand what communication is? What is the mechanism of communication?

Let's start with a discussion of what is communication? Communication refers to the exchange and transmission of information between a person and a person or a person and nature through a certain act or medium, which in a broad sense refers to the need for information to be transmitted to another party in an arbitrary medium, without violating the wishes of the parties, by any means, or by arbitrary media. And the communication here is in the same LAN, a user to send information to other users of the process.

then what is the mechanism of the passage? The Javaio communication here is like this, first we need a server, and there is one or more users. The transfer of information between users and users must be through the server, the role of the server is to process the information sent by various users, and make various execution of various directives.

Finally, let's look at how to implement our simple communication through code:

1. Server:

1, first we need a server, we can use our computer to build a server, how to build it? Java provides the ServerSocket class, I can use this class to build a server, when instantiating this class need to specify a port (general computer has 256*256 ports, it is recommended to use more than 9000 ports, to avoid some popular port conflicts), And the server's IP address is the computer's local area network under the IP address, It is worth noting that when our computer in different LAN is the IP address will be different!!! In general, use the ipconfig command at the command line to view the IP address of our computer. Key code :

public void Createserver (int port) {

try {

Serversocket=new ServerSocket (port);

} catch (IOException e) {

E.printstacktrace ();

}

}

2, the server has been set up, the next thing the server needs to do is to wait for the user to connect to the server, only to do the next, otherwise, has been waiting for users to go online. Waiting for the user's client connection server is required to use Java to provide the socket class, the role of this class, the author explained as the role of the interface, where we can only use a server, but a server with multiple interfaces, each interface can connect a user, and the server can manage all the interfaces, To achieve the goal of managing all users

Key code:

public void Connect () {

Socket socket= serversocket.accept ();

When an interface is obtained, it will be blocked and will stay here until a user connects to the server before the next statement is executed.

System.out.println ("There is a client Access server");

}

3, now our simplest server is set up, but this server has only one function, is to let users connect, and then the end. How to let the user connect in real-time continuously open it? Very simply, we just use a while (true) loop to let the program not end. Next, look at how to implement the server to read the user's message, and to send messages to the user? First we need an IO stream, which is called IO Communication, where the sending and reading information is implemented via IO stream. Just mentioned above a server has multiple interfaces, an interface can connect a user, now we can be based on the interface to get out of our IO stream, while it is worth noting that an interface gets out of the IO stream can only read and send the interface interface to connect the user. For example: interface A is connected to a user, so the IO stream obtained by the A interface can only read the information sent by a user, and send a message to a user.

key code :

while (true) {

try {

Socket socket=serversocket.accept ();

System.out.println ("There is a client Access server");

outputstream output=socket.getoutputstream ();//Gets the output stream for sending information to the user

InputStream Input=socket.getinputstream ();//Gets the input stream, the user reads the information sent by the user

Output.write ("welcome!"). GetBytes ());//Send "welcome" to the user

Input.read ();//Read a byte of a user message, call one byte at a time, have blocking effect, if the user does not send a message, it will stay here until a message is sent over.

} catch (IOException e) {

E.printstacktrace ();

}          

       }

}

In this way, our server has the most basic function, when the user connects in, the server can read the user's information, can send information to the user. But carefully pondering the code above or executing it will find that the server can only send and read information to a connected user. Why is this? To analyze, first the user executes the Socket socket=serversocket.accept () will execute, this line of command, for the user to open the interface, and to the input.read (); If the user has not sent a message to the server, which program will be blocked in this statement here, and other users want to connect in the need to execute socket socket=serversocket.accept (), this sentence, but the program has been stuck in input.read (); Here, so it will appear that only one user can be connected. This also shows that the main thread of this can do one thing, when it comes to threading, we should solve such a problem, we cannot only have a user, that does not reach our purpose of communication. So here we need to use multiple threads to solve this problem for us. The following will be a detailed analysis of how to solve this problem.

since our main thread can only do one thing, then we can let the server information read and write in a sub-thread, each user by a child thread user information read and send, this thread should have all the information of that user, also called this thread is the interface thread, All interface threads can be accessed indirectly through an interface thread in the server. Key code :

Arraylist<users> userlist=new arraylist<users> ();

while (true) {

try {

Socket socket=serversocket.accept ();

System.out.println ("There is a client Access server");

Users oneuser=new User (socket,username, password);

Userlist.add (Oneuser);

chatmanage chat=new chatmanage (socket,username);//Pass a the socket used to read and write information, and then pass a user name to identify the chat thread. User name can

specified by the server or by the user.

Chat.start ();//Start thread.

} catch (IOException e) {

E.printstacktrace ();

}          

       }

}

public class Chatmanage extends thread{

Socket socket;

String UserName;

Public Chatmanage (Socket socket,string userName) {

This.socket=socket;

This.username=username;

}

public void Run () {

while (true) {

Get IO Stream

InputStream Input=socket.getinputstream ();

Ouputstream Output=socket.getoutputstream ();

You can use the IO stream to read and send messages, ....

}

}

}

In order to better manage each user connected to the server, we can write a user class for the user

Each user is saved in a dynamic array.

public class Users {

String password;

String sex= "man";

String account= "123456";

String UserName;

private socket socket;

Public Users (Socket socket,string username,string password) {

this.socket=socket;

this.username=username;

This.password=password;

      }            

Java to implement IO communication (server 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.