java - 如何使示例 MulticastChat 运行?

标签 java multithreading server client multicast

到目前为止,我已经定义了端口号和 inetaddress,但我仍然不明白为什么我无法让下面的示例呈现 GUI?如果社区中有人能指出我所犯的错误,我将不胜感激。谢谢。

下面是 GUI 格式的多播完整程序的源代码,它使用点对点网络实现,通过 TCP 协议(protocol)传递消息,并使用同步方法实现多线程,将消息发送到迄今为止连接的所有对等点。

/* Multicast Peer to Peer chat application that uses TCP protocol to chat 
 * to two users at a time or adding more clients could be developed into 
 * a group chat communicating amongst multiple members of the same chat. 
 *
*/

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class MulticastChat implements Runnable, WindowListener, ActionListener {
   protected InetAddress group;
   protected int port = 2343;

  public MulticastChat (InetAddress group, int port) {
     this.group = group;
     this.port = port;
     initAWT();
   }

   protected Frame frame;
   protected TextArea output;
   protected TextField input;
   private static final Logger logger =
      Logger.getLogger(MulticastChat.class.getName());


   protected void initAWT () {
     frame = new Frame
       ("MulticastChat [" + group.getHostAddress () + ":" + port + "]");
     frame.addWindowListener (this);
     output = new TextArea ();
     output.setEditable (false);
     input = new TextField ();
     input.addActionListener (this);
     frame.setLayout (new BorderLayout ());
     frame.add (output, "Center");
     frame.add (input, "South");
     frame.pack ();
   }

    protected Thread listener;

    public synchronized void start() throws IOException {
     if (listener == null) {
       initNet ();
       listener = new Thread (this);
       listener.start ();
       frame.setVisible (true);
     }
   }

   protected MulticastSocket socket;
   protected DatagramPacket outgoing, incoming;

   protected void initNet () throws IOException {
     socket = new MulticastSocket (port);
     socket.setTimeToLive (5);
     socket.joinGroup (group);
     outgoing = new DatagramPacket (new byte[1], 1, group, port);
     incoming = new DatagramPacket (new byte[65508], 65508);
   }

   public synchronized void stop () throws IOException {
     frame.setVisible (false);
     if (listener != null) {
       listener.interrupt ();
       listener = null;
       try {
         socket.leaveGroup (group);
       } finally {
         socket.close ();
       }
     }
   }

   @Override
   public void windowOpened (WindowEvent event) {
     input.requestFocus ();
   }

   @Override
   public void windowClosing (WindowEvent event) {
     try {
       stop ();
     } catch (IOException ex) {
           logger.log(Level.WARNING,"WindowClosing IOException",ex);
     }
   }

   @Override
   public void windowClosed (WindowEvent event) {}
   @Override
   public void windowIconified (WindowEvent event) {}
   @Override
   public void windowDeiconified (WindowEvent event) {}
   @Override
   public void windowActivated (WindowEvent event) {}
   @Override
   public void windowDeactivated (WindowEvent event) {}

   @Override
   public void actionPerformed (ActionEvent event) {
     try {
       byte[] utf = event.getActionCommand ().getBytes ("UTF8");
       outgoing.setData (utf);
       outgoing.setLength (utf.length);
       socket.send (outgoing);
       input.setText ("");
     } catch (IOException ex) {
       handleIOException (ex);
     }
   }

   protected synchronized void handleIOException (IOException ex) {
     if (listener != null) {
       output.append (ex + "\n");
       input.setVisible (false);
       frame.validate ();
       if (listener != Thread.currentThread ())
         listener.interrupt ();
       listener = null;
       try {
         socket.leaveGroup (group);
       } catch (IOException ignored) {
       }
       socket.close ();
     }
   }

   @Override
   public void run () {
     try {
       while (!Thread.interrupted ()) {
         incoming.setLength (incoming.getData ().length);
         socket.receive (incoming);
         String message = new String
           (incoming.getData (), 0, incoming.getLength (), "UTF8");
         output.append (message + "\n");
       }
     } catch (IOException ex) {
        handleIOException (ex);
     }
   }

// Unfortunately the example given didn't have any comments for me to try 
// to understand how to get the example operating. 
   public static void main (String[] args) throws IOException {
     if ((args.length != 1) || (!args[0].contains(":"))){
       throw new IllegalArgumentException
         ("Syntax: MulticastChat <group>:<port>");
     } else {

    int idx = args[0].indexOf (":");
       InetAddress group = InetAddress.getByName (args[0].substring (0, idx));
     int port = Integer.parseInt (args[0].substring (idx + 1));

    MulticastChat chat = new MulticastChat (group, port);
                chat.start();
       }
     }
   }

这是出现的错误:

Exception in thread "main" java.lang.IllegalArgumentException: Syntax: MulticastChat <group>:<port>
at MulticastChat.main(MulticastChat.java:167)

最佳答案

按如下方式更改您的主要方法

public static void main(String[] args) throws IOException {

        // Define default host name
        String host = "228.5.6.7";
        // Define default port
        int port = 8804;
        if ((args.length != 1) || (!args[0].contains(":"))) {
            // throw new IllegalArgumentException("Syntax: MulticastChat <group>:<port>");
        } else {

            int idx = args[0].indexOf(":");
            host = args[0].substring(0, idx);
            port = Integer.parseInt(args[0].substring(idx + 1));
        }

        InetAddress group = InetAddress.getByName(host);
        MulticastChat chat = new MulticastChat(group, port);
        chat.start();
    }

关于java - 如何使示例 MulticastChat 运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59080398/

相关文章:

java - 在 websphere 中启动应用程序时出现异常 java.lang.NoSuchMethodError : org/w3c/dom/Node. getTextContent()Ljava/lang/String

java - 在 Java 8 中使用先前链接的 thenCompose lambda 的值

multithreading - 如何为 RustBox 实现 Sync?

python - 简单服务器-客户端程序的问题

mysql - 是否可以在本地项目中使用在线数据库?

java - 为什么绘制类不能与 setDefault LookAndFeel Decorated(true) 一起使用

java - Android开发中Fragment之间传递对象数组列表

java - 多线程 Java Web 服务器

python - isAlive() 是否可以在调用 start() 后立即为 False 因为线程尚未启动?

linux - -bash :/usr/local/cpanel/3rdparty/bin/perl: No such file or directory - linux server kind of crashed