Java implementation of socket chat program based on TCP

For beginners who are not deep in the programming industry or who have already understood it, when learning a new technology, they are very eager to have a complete demo with comments. I deeply understand that there are many online examples, but they are very complex and incomplete. Writing code should not be careless. If it is wrong, it can't run. This is even more troublesome for beginners, because he doesn't know what's wrong. Blindly changing can only add mistakes to mistakes. Finally, we have to look for examples that can run directly and imitate them.

The following is a complete example written by the blogger when learning java socket, with complete comments. It is a simple chat program, but it can set any number of users to log in at the same time, and then communicate with each other. Bloggers only log in at the same time on their own computers, and then communicate with each other.

The general idea of the procedure is as follows:

① As a server, that is, the requested connection end is different from the active request connection end. Secondly, it may be connected many times by other users, so you as a server will have many connections. Similarly, you as a client will also have many connections. In order to make the program easier to understand, when bloggers write, they set up many containers to place different things separately. Do decoupling, or you won't be able to distinguish yourself at the back.

② You can write two classes at a time, client1, client2, client1 as the server, client2 as the client, and the client connects to the server, so as to realize the server function of client1 and the client function of client2. Each time you implement a function, first integrate the functions of the server and the client, exchange roles, and see if there are errors.

③ When two users are implemented, write the third class client3, and the code is copy and paste. Of course, you can also directly create a client3 class, and then directly change the port number and user name in the main method of the class. After the third is implemented, the fourth and fifth are implemented.

The following is the specific code:

design sketch:

Source download: Java TCP based socket chat program

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>