在Java中的线程之间进行通信

时间:2013-03-29 04:58:42

标签: java multithreading network-programming

我正在尝试制作一个允许两个或更多客户端之间进行通信的程序。我从一个站点获取了大部分源代码,但是我无法找到如何使两个客户端实际显示另一个客户端所说的内容。由于它们在自己的线程中运行,我认为服务器只将文本提供给发送者的线程,而不是将其提供给所有连接的人。

package Server;
import java.net.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;

public class Server extends JFrame
{   
//A JTextArea to hold the information received from clients
JTextArea chatBox = new JTextArea();

public static void main(String[] args)
{
    new Server();
}

public Server()
{
    //We need to set up a layout for our window
    setLayout(new BorderLayout());
    //Only display text, do not allow editing
    chatBox.setEditable(false);
    //Add our chatbox in the center with scrolling abilities
    add(new JScrollPane(chatBox), BorderLayout.CENTER);

    setTitle("Chat Server");
    setSize(550,400);
    //If the user closes then exit out
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Show the frame
    setVisible(true);

    //We need a try-catch because lots of errors can be thrown
    try {
        ServerSocket sSocket = new ServerSocket(8123);
        chatBox.append("Server started at: " + new Date()+"\n");

        //Loop that runs server functions
        while(true) {
            //Wait for a client to connect
            Socket socket = sSocket.accept();
            int Port = socket.getPort();
            InetAddress IP = socket.getInetAddress();
            System.out.println("INFO: Incoming connection from: "+IP+":"+Port);
            chatBox.append("INFO: Incoming connection from: "+IP+":"+Port+"\n");

            //Create a new custom thread to handle the connection
            ClientThread cT = new ClientThread(socket);

            //Start the thread!
            new Thread(cT).start();

        }
    } catch(IOException exception) {
        System.out.println("Error: " + exception);
    }
}

//Here we create the ClientThread inner class and have it implement Runnable
//This means that it can be used as a thread
class ClientThread implements Runnable
{
    Socket threadSocket;

    //This constructor will be passed the socket
    public ClientThread(Socket socket)
    {
        //Here we set the socket to a local variable so we can use it later
        threadSocket = socket;
    }

    public void run()
    {

        //All this should look familiar
        try {
            //Create the streams
            PrintWriter output = new PrintWriter(threadSocket.getOutputStream(), true);
            BufferedReader input = new BufferedReader(new InputStreamReader(threadSocket.getInputStream()));

            //Tell the client that he/she has connected
            output.println("You have connected at: " + new Date());
            chatBox.append("Client connected\n");


                //This will wait until a line of text has been sent
                String chatInput = input.readLine();
                //Add the chat to the text box
                chatBox.append(chatInput+"\n");
                System.out.println(chatInput);
                output.println(chatInput);
            } catch(IOException exception) {
            System.out.println("ERROR: " + exception);
            chatBox.append("ERROR: "+exception);
        } 
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可能正在寻找一个发布/订阅方案,其中来自服务器的单个消息将传播到所有订阅者。尝试使用JMS。您可以在PointToPoint vs Publish/subscribe model in JMS?

找到更多详细信息