"Java" socket+ multithreaded implementation console chat room

Source: Internet
Author: User
Tags sendmsg

Reprint please specify the original address: http://www.cnblogs.com/ygj0930/p/5827212.html

Structure diagram of the chat room program:

Schema Explanation:

The server server is the equivalent of a broker, the client terminal program transmits information to the server, and the server distributes the information to other clients for instant communication.

Required Technology:

1: Data transfer.

The transfer of information between the server and the client is accomplished through the data channel, where a client connects to the server and a data channel is set up between the client and the server.

This data channel is implemented through a socket: Each client establishes a connection to the server through a socket, which is an "endpoint" of the channel. Server-side ServerSocket Once a client access is detected, the Accept () method returns a socket object immediately to the client's socket, which is another "endpoint" of the channel. "Two points to build a straight line", of course, here is not necessarily straight (nonsense). In short, a channel like a water pipe in this way to connect a client and the server. The next thing is to transfer the data we want to transmit through the data channel, just like the water pipes, the data is the water.

2: Continuous monitoring.

Instant chat requires a client (the chat) to immediately update to the interface of all clients connected to the server, this simple, learned while loop should be able to immediately think: I use a while () statement continuously from the data channel detection data is not become? Once the data channel has information, immediately take it out, on the client display is OK.

However! It's not over yet. Each client maintains the state of receiving user input continuously. You can't just send a message to a client and shut it down?

So the problem, but also to keep listening to the server to send the message, but also to maintain continuous monitoring keyboard input, then the two while loop exactly how to arrange it?

The easiest mistake to make here is to nest another while loop with one while loop. For example, the following code:

while ((MSG1 = Br.readline ()) = null) {
System.out.println (MSG1);
while (true) {
MSG2 = Re.readline ();
Pw.println (MSG2);
}

The outer loop continuously listens to the data channel, and once it has the information sent by the server, it is extracted and displayed to the client. The inner loop continues to monitor the keyboard input, which is transmitted to the server via PW (data channel, etc.).

The error here is that the inner loop is a dead loop and does not stop, so the client keeps typing information to the server, but the information is not updated to other clients. Because the client code stays in the inner loop, there is no way out of the code that listens and extracts the data channel information.

There is also a case, that is, the client input information, but did not show it, Crazy press the keyboard did not see a word. But when the server program is closed, you see a lot of information just entered in the Client program window.

The reason for this error is, in contrast to the above, that the while loop that listens on the data channel blocks the execution of the next while loop (the receiving keyboard input section). The code is as follows:

BufferedReader br = new BufferedReader (new InputStreamReader (socket. getInputStream ()));

String MSG1;

while ((MSG1 = Br.readline ()) = null) {
System.out.println (MSG1);
}

BufferedReader re = new BufferedReader (new InputStreamReader (system.in));
PrintWriter pw = new PrintWriter (Socket.getoutputstream (), true);
String MSG2;
while (true) {
MSG2 = Re.readline ();
Pw.println (MSG2);
}

The above one while loop continuously listens to the data channel (the server sends the information to the client), keeps waiting to receive the information state, causes the following code not to execute, therefore the client cannot receive the user input, the pounding keyboard also is useless.

When the server program is closed, the data channel is broken, no longer listens, and instead runs to the following while loop, so it can receive user input.

So what is the correct posture? That is: parallel.

While a while loop is running, another while loop also runs. Two while loops do not have a succession of points.

To achieve parallelism, you need to use multithreaded technology. "Multithreading is what I will not talk about, basically can do this project people are learning multi-threading to practice the bar ha haha ~"

The correct and complete code is posted for reference only. If you are used to cope with the homework assigned by the teacher, be careful to crash with other classmates-_-:

Server.java:

Import java.net.*;
Import java.io.*;
Import java.util.*;

public class Server
{int port;
List<socket> clients;
ServerSocket server;
public static void Main (string[] args)
{
New Server ();
}
Public Server ()
{
try{

port=8080;
Clients=new arraylist<socket> ();
Server=new ServerSocket (port);

while (true)
{
Socket socket=server.accept ();
Clients.add (socket);
Mythread mythread=new Mythread (socket);
Mythread.start ();
}



}catch (Exception ex)
{
}
}
Class Mythread extends Thread
{
Socket Ssocket;
Private BufferedReader BR;
Private PrintWriter PW;
Public String msg;
Public Mythread (Socket s)
{
Ssocket=s;
}
public void Run ()
{

try{
br = new BufferedReader (New InputStreamReader (Ssocket.getinputstream ()));
msg = "Welcome" "+ ssocket.getinetaddress () +" "Enter the chat room! The current chat room has ""
+ clients.size () + "person";

Sendmsg ();

while (msg = Br.readline ()) = null) {

msg = "" "+ ssocket.getinetaddress () +" "said" + msg;
Sendmsg ();

}
}catch (Exception ex)
{

}
}
public void sendmsg ()
{
try{
SYSTEM.OUT.PRINTLN (msg);

for (int i = Clients.size ()-1; I >= 0; i--)
{
Pw=new PrintWriter (Clients.get (i). Getoutputstream (), true);
PW.PRINTLN (msg);
Pw.flush ();
}
}catch (Exception ex)
{
}
}

}

}

Client.java:

Import java.io.*;
Import java.net.*;
Import java.util.*;

public class client{
public int port=8080;
Socket Socket=null;

public static void Main (string[] args)
{
New Client ();
}

Public Client ()
{

try {
Socket=new Socket ("127.0.0.1", port);

New Cthread (). Start ();

BufferedReader br = new BufferedReader (New InputStreamReader (socket
. getInputStream ()));
String MSG1;
while ((MSG1 = Br.readline ()) = null) {

System.out.println (MSG1);
}
}catch (Exception e) {
}
}

Class Cthread extends Thread
{

public void Run () {
try {

BufferedReader re = new BufferedReader (new InputStreamReader (system.in));
PrintWriter pw = new PrintWriter (Socket.getoutputstream (), true);
String MSG2;

while (true) {

MSG2 = Re.readline ();
Pw.println (MSG2);
}
}catch (Exception e) {
E.printstacktrace ();
}


}
}

}

Old habits, to a summary: using the socket to build a data channel (Inputstream/outputstream), with multi-threaded simultaneous running two while to implement monitoring and updating, is the chat room technology.

(I am a novice, I implore old yards farmers to correct me.) Appreciate! If you need to reprint and exchange, please leave a message at the comment Office to let me know, thank you)

"Java" socket+ multithreaded implementation console chat room

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.