簡體   English   中英

在Java中的線程之間進行通信

[英]Communicating Between Threads In Java

我正在嘗試制作一個允許兩個或多個客戶端之間進行通信的程序。 我從網站上獲取了大部分資源,但是我找不到如何使兩個客戶真正顯示另一個客戶所說的話。 由於它們在自己的線程中運行,因此我認為服務器僅將文本返回給發件人的線程,而不是將文本提供給所有連接的人。

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);
        } 
        }
    }
}

您可能正在尋找一種發布/訂閱方案,在這種情況下,來自服務器的一條消息將傳播到所有訂閱者。 嘗試使用JMS。 您可以在此處找到更多詳細信息。PointToPoint與JMS中的發布/訂閱模型?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM