1

我正在学习正确的线程、套接字和服务器/客户端

我正在开发一个程序,但需要它来做这样的事情

Client1-     - Client2
        -   -
  ^      - -    ^
  |     -   -   |
Server1-     -Server 2

箭头显示如何进行通信 Client1 的输出被发送到 Server2,服务器 2 将其转发给 Client 2

Client2 的输出被发送到 server1...等。

因此,客户端与彼此的服务器对话并将消息转发给彼此。现在我的代码只适用于单个服务器/多个客户端

服务器:

import java.io.*;
import java.net.*;
import javax.swing.*;

public class MultiThreadChatServerSync 
{

  private static ServerSocket serverSocket = null;
  private static Socket clientSocket = null;

  private static final int maxClientsCount = 10;
  private static final clientThread[] threads = new clientThread[maxClientsCount];
  private JButton stopStart;
  private JTextArea chat, event, chat2;
  private JTextField tPortNumber;


  public static void main(String args[])
  { 
      String Regex = "[0-9]+";
    int portNumber = 2222;
    // The default port number.
     while(true)
     { 
     String ports= JOptionPane.showInputDialog("Port Number:");
            if(ports.matches(Regex))
            {
                break;
            }
            else
                JOptionPane.showConfirmDialog(null, "Invalid port number, please enter a valid port");

     }


    if (args.length < 1) 
    {
      System.out.println("Usage: java MultiThreadChatServerSync <portNumber>\n" + "Now using port number=" + portNumber);
    } else 
    {
      portNumber = Integer.valueOf(args[0]).intValue();
    }

    /*
     * Open a server socket on the portNumber (default 2222). Note that we can
     * not choose a port less than 1023 if we are not privileged users (root).
     */
    try 
    {
      serverSocket = new ServerSocket(portNumber);
    }
    catch (IOException e)
    {
      System.out.println(e);
    }

    /*
     * Create a client socket for each connection and pass it to a new client
     * thread.
     */
    while (true)
    {
      try {
        clientSocket = serverSocket.accept();
        int i = 0;
        for (i = 0; i < maxClientsCount; i++) {
          if (threads[i] == null) {
            (threads[i] = new clientThread(clientSocket, threads)).start();
            break;
          }
        }
        if (i == maxClientsCount) {
          PrintStream os = new PrintStream(clientSocket.getOutputStream());
          os.println("Server too busy. Try later.");
          os.close();
          clientSocket.close();
        }
      } catch (IOException e) {
        System.out.println(e);
      }
    }
  }
}

/*
 * The chat client thread. This client thread opens the input and the output
 * streams for a particular client, ask the client's name, informs all the
 * clients connected to the server about the fact that a new client has joined
 * the chat room, and as long as it receive data, echos that data back to all
 * other clients. The thread broadcast the incoming messages to all clients and
 * routes the private message to the particular client. When a client leaves the
 * chat room this thread informs also all the clients about that and terminates.
 */
class clientThread extends Thread {

  private String clientName = null;
  private DataInputStream is = null;
  private PrintStream os = null;
  private Socket clientSocket = null;
  private final clientThread[] threads;
  private int maxClientsCount;

  public clientThread(Socket clientSocket, clientThread[] threads) {
    this.clientSocket = clientSocket;
    this.threads = threads;
    maxClientsCount = threads.length;
  }

  public void run() {
    int maxClientsCount = this.maxClientsCount;
    clientThread[] threads = this.threads;

    try {
      /*
       * Create input and output streams for this client.
       */
      is = new DataInputStream(clientSocket.getInputStream());
      os = new PrintStream(clientSocket.getOutputStream());
      String name;
      while (true)
      {
        os.println("Enter your name.");
        name = is.readLine().trim();
        if (name.indexOf('@') == -1) {
          break;
        } else {
          os.println("The name should not contain '@' character.");
        }
      }

      /* Welcome the new the client. */
      os.println("Welcome " + name + " to the waiting room.\nTo leave enter /quit in a new line.");



      synchronized (this) 
      { for (int i = 0; i < maxClientsCount; i++) 
        {
          if (threads[i] != null && threads[i] == this) 
          {
            clientName = "@" + name;
            break;
          }
        }
        for (int i = 0; i < maxClientsCount; i++) 
        {
          if (threads[i] != null && threads[i] != this)
          {
            threads[i].os.println("*** A new user " + name + " entered the chat room !!! ***");
          }
        }
      }
      /* Start the conversation. */
      while (true) 
      {
        String line = is.readLine();
        if (line.startsWith("/quit"))
        {
          break;
        }
        if (line.startsWith("Play"))
        {
          for (int i = 0; i < maxClientsCount; i++) 
        {
          if (threads[i] != null && threads[i] != this)
          {
            threads[i].os.println("Would you like to play a round of Paper Rock Scissors?");
            while(true)
            {
                String gameline = threads[i].is.readLine();
                if(gameline.toLowerCase().startsWith("yes"))
                {
                      os.println("A game has been intiated");

                }
                if(gameline.toLowerCase().startsWith("no"))
                {
                    os.println("Game invite declined");
                }
                else
                {


                }

            }
          }
        } 

            //initiate game

        }
        /* If the message is private sent it to the given client. */
        if (line.startsWith("@")) 
        {
          String[] words = line.split("\\s", 2);
          if (words.length > 1 && words[1] != null) 
          {
            words[1] = words[1].trim();
            if (!words[1].isEmpty()) 
            {
              synchronized (this)
              {
                for (int i = 0; i < maxClientsCount; i++) {
                  if (threads[i] != null && threads[i] != this
                      && threads[i].clientName != null
                      && threads[i].clientName.equals(words[0])) {
                    threads[i].os.println("<" + name + "> " + words[1]);
                    /*
                     * Echo this message to let the client know the private
                     * message was sent.
                     */
                    this.os.println(">" + name + "> " + words[1]);
                    break;
                  }
                }
              }
            }
          }
        } else
        {
          synchronized (this) 
          {
            for (int i = 0; i < maxClientsCount; i++)
            {
              if (threads[i] != null && threads[i].clientName != null) {
                threads[i].os.println("<" + name + "> " + line);
              }
            }
          }
        }
      }
      synchronized (this) 
      {
        for (int i = 0; i < maxClientsCount; i++)
        {
          if (threads[i] != null && threads[i] != this
              && threads[i].clientName != null) {
            threads[i].os.println("*** The user " + name + " is leaving the chat room !!! ***");
          }
        }
      }
      os.println("*** Bye " + name + " ***");

      synchronized (this)
      {
        for (int i = 0; i < maxClientsCount; i++) {
          if (threads[i] == this) {
            threads[i] = null;
          }
        }
      }


      //close all
      is.close();
      os.close();
      clientSocket.close();
    }
    catch (IOException e)
    {
    }
  }
}

客户:

import java.io.*;
import java.net.*;
import javax.swing.JPanel;

public class MultiThreadChatClient implements Runnable {

  private static Socket clientSocket = null;
  private static PrintStream os = null;
  private static DataInputStream is = null;
  private static BufferedReader inputLine = null;
  private static boolean closed = false;






  public static void main(String[] args)
  {

    // The default port.
    int portNumber = 2222;
    // The default host.
    String host = "localhost";

    if (args.length < 2)
    {
      System.out.println("Usage: java MultiThreadChatClient <host> <portNumber>\n" + "Now using host=" + host + ", portNumber=" + portNumber);
    } else 
    {
      host = args[0];
      portNumber = Integer.valueOf(args[1]).intValue();
    }

    /*
     * Open a socket on a given host and port. Open input and output streams.
     */
    try 
    {
      clientSocket = new Socket(host, portNumber);
      inputLine = new BufferedReader(new InputStreamReader(System.in));
      os = new PrintStream(clientSocket.getOutputStream());
      is = new DataInputStream(clientSocket.getInputStream());
    }
    catch (UnknownHostException e)
    {
      System.err.println("Don't know about host " + host);
    } 
    catch (IOException e) {
      System.err.println("Couldn't get I/O for the connection to the host "
          + host);
    }

    /*
     * If everything has been initialized then we want to write some data to the
     * socket we have opened a connection to on the port portNumber.
     */
    if (clientSocket != null && os != null && is != null)
    {
      try 
      {

        /* Create a thread to read from the server. */
        new Thread(new MultiThreadChatClient()).start();
        while (!closed) {
          os.println(inputLine.readLine().trim());
        }
        /*
         * Close the output stream, close the input stream, close the socket.
         */
        os.close();
        is.close();
        clientSocket.close();
      } catch (IOException e) {
        System.err.println("IOException:  " + e);
      }
    }
  }

  /*
   * Create a thread to read from the server. (non-Javadoc)
   * 
   * @see java.lang.Runnable#run()
   */
  public void run()
  {
    /*
     * Keep on reading from the socket till we receive "Bye" from the
     * server. Once we received that then we want to break.
     */
    String responseLine;
    try 
    {
      while ((responseLine = is.readLine()) != null) 
        {
        System.out.println(responseLine);
        if (responseLine.indexOf("*** Bye") != -1)
          break;
        }
      closed = true;
    } 
    catch (IOException e) 
    {
      System.err.println("IOException:  " + e);
    }
  }
}

我只是在寻找有关如何按照我的要求链接服务器的一些信息。

该应用程序通常用于通过聊天客户端进行的基于文本的游戏。例子。用户 1 邀请用户 2 玩游戏(玩家 2 以是或否响应) 双方开始游戏 用户 1 发送一个号码,玩家 2 发送一个号码。

如果数字是奇数玩家 1 获胜或偶数玩家 2 获胜(所以我计划一个比较 if 语句,一旦我能弄清楚如何正确处理流,这将很容易做到)

4

0 回答 0