单击“连接”时没有任何反应

发布于 2024-10-30 12:52:23 字数 5075 浏览 1 评论 0原文

注意:我已将我的机器设置为服务器和客户端

这是我的完整代码:

客户端

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.lang.Thread;

class chatboxClient {

    JFrame fr;
    JPanel p;
    JButton send;
    JTextArea ta;
    JRadioButton rb;
    static chatboxServer cbS=new chatboxServer();
    public Thread connectThread;

    chatboxClient() {
        fr=new JFrame("ChatBox_CLIENT");
        p=new JPanel();
        send=new JButton("send");
        send.addActionListener(new ActionListener() {       // action listener for send
                public void actionPerformed(ActionEvent ae) {
                    sendActionPerformed(ae);
                }
            });

        ta=new JTextArea();
        ta.setRows(20);
        ta.setColumns(20);
        rb=new JRadioButton("Connect");               // action listener for connect
        rb.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    connectActionPerformed(ae); 
                }
            });
        fr.add(p);
        p.add(ta);
        p.add(rb);
        p.add(send);
        fr.setSize(500,500);
        fr.setResizable(false);
        fr.setVisible(true);
    }
    public void connectActionPerformed(ActionEvent ae) {
        EnsureEventThread();
        CreateConnectThread();
    }
    public void CreateConnectThread() {             // Seperate Thread created for handling 'connect'
        Runnable r=new Runnable() {
                public void run() {
                    connect();
                }
            };
        connectThread=new Thread(r,"Connect Thread");
        connectThread.start();
    }

    public void connect() {
        try {
            cbS.Laccept();
            rb.setEnabled(false);
            JOptionPane.showMessageDialog(new JFrame()," Sockets InterConnected!");
        } catch(Exception exc) {
            JOptionPane.showMessageDialog(new JFrame()," Connection Error..");
        }
    }
    public void sendActionPerformed(ActionEvent ae) {
        try { 
            String s=ta.getText();
            InetAddress address=InetAddress.getLocalHost();
            DatagramSocket ds=new DatagramSocket(3000,address);
            byte buffer[]=new byte[800];
            buffer=s.getBytes();
             Runnable rR=new Runnable() {   // Seperate thread for 'Receive'
                public void run() {
                  cbS.Receive(s);
                }
             };
             Thread TReceive=new Thread(rR,"Receive Thread");
             TReceive.start();
            DatagramPacket dp=new DatagramPacket(buffer,buffer.length,address,3000);
            if(true) {
                ds.send(dp);

                cbS.Receive(s); // call Receive method of chatboxServer class
            }
            catch(Exception exc) {
                JOptionPane.showMessageDialog(new JFrame(),"Error sending Message");
            }
        }  
    }

    public void EnsureEventThread() {
        try { 
            if(SwingUtilities.isEventDispatchThread()) 
                return;
        } catch(Exception exc) {
            System.out.println(exc);
        }
    }


    public static void main(String args[]) {
        chatboxClient cbC= new chatboxClient();
    }
}

服务器端

import java.awt.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;

class chatboxServer {
    JFrame fr;
    JPanel p;
    JTextArea ta;
    JButton send;
    ServerSocket ss;
    byte buffer[]=new byte[800];

    chatboxServer() {
        fr=new JFrame("ChatBox_SERVER");
        p=new JPanel();
        ta=new JTextArea();
        ta.setRows(20);
        ta.setColumns(20);
        send=new JButton("send");
        fr.add(p);
        p.add(ta);
        p.add(send);
        fr.setVisible(true);
        fr.setSize(500,500);
        fr.setResizable(false);

    }

    public void Receive(String sm) {
        try {
            buffer=sm.getBytes();
            InetAddress address=InetAddress.getLocalHost();
            DatagramSocket ds=new DatagramSocket(3000,address);
            DatagramPacket dp=new DatagramPacket(buffer,buffer.length);
            ds.receive(dp);
            String s=new String(dp.getData(),0,dp.getLength());
            ta.setText(s);  
        }    catch(Exception exc) {
            System.out.println("Error Receiving..");
        }
    }

    public void Laccept() {
        try {
            ss=new ServerSocket(3000);     // First making port number 3000 on server to listen
            Socket s=ss.accept();
        }   catch(Exception exc) {
            JOptionPane.showMessageDialog(new JFrame(),"Accept Failed :3000 :Server Side");
        }  
    }
}

问题---< /强> 当我点击连接时什么也没有发生。问题是什么 ?

我检查过的一件事:程序在 ss.accept() 处等待;这就是我认为 Laccept() 调用旁边的语句不起作用的原因...

请注意我通过上面代码的目的是向服务器发送消息,服务器与客户端运行的机器是同一台机器

请清楚地解释一下我应该做什么?

Note: I have made my machine both server and client

This is my complete code:

Client Side

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.lang.Thread;

class chatboxClient {

    JFrame fr;
    JPanel p;
    JButton send;
    JTextArea ta;
    JRadioButton rb;
    static chatboxServer cbS=new chatboxServer();
    public Thread connectThread;

    chatboxClient() {
        fr=new JFrame("ChatBox_CLIENT");
        p=new JPanel();
        send=new JButton("send");
        send.addActionListener(new ActionListener() {       // action listener for send
                public void actionPerformed(ActionEvent ae) {
                    sendActionPerformed(ae);
                }
            });

        ta=new JTextArea();
        ta.setRows(20);
        ta.setColumns(20);
        rb=new JRadioButton("Connect");               // action listener for connect
        rb.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    connectActionPerformed(ae); 
                }
            });
        fr.add(p);
        p.add(ta);
        p.add(rb);
        p.add(send);
        fr.setSize(500,500);
        fr.setResizable(false);
        fr.setVisible(true);
    }
    public void connectActionPerformed(ActionEvent ae) {
        EnsureEventThread();
        CreateConnectThread();
    }
    public void CreateConnectThread() {             // Seperate Thread created for handling 'connect'
        Runnable r=new Runnable() {
                public void run() {
                    connect();
                }
            };
        connectThread=new Thread(r,"Connect Thread");
        connectThread.start();
    }

    public void connect() {
        try {
            cbS.Laccept();
            rb.setEnabled(false);
            JOptionPane.showMessageDialog(new JFrame()," Sockets InterConnected!");
        } catch(Exception exc) {
            JOptionPane.showMessageDialog(new JFrame()," Connection Error..");
        }
    }
    public void sendActionPerformed(ActionEvent ae) {
        try { 
            String s=ta.getText();
            InetAddress address=InetAddress.getLocalHost();
            DatagramSocket ds=new DatagramSocket(3000,address);
            byte buffer[]=new byte[800];
            buffer=s.getBytes();
             Runnable rR=new Runnable() {   // Seperate thread for 'Receive'
                public void run() {
                  cbS.Receive(s);
                }
             };
             Thread TReceive=new Thread(rR,"Receive Thread");
             TReceive.start();
            DatagramPacket dp=new DatagramPacket(buffer,buffer.length,address,3000);
            if(true) {
                ds.send(dp);

                cbS.Receive(s); // call Receive method of chatboxServer class
            }
            catch(Exception exc) {
                JOptionPane.showMessageDialog(new JFrame(),"Error sending Message");
            }
        }  
    }

    public void EnsureEventThread() {
        try { 
            if(SwingUtilities.isEventDispatchThread()) 
                return;
        } catch(Exception exc) {
            System.out.println(exc);
        }
    }


    public static void main(String args[]) {
        chatboxClient cbC= new chatboxClient();
    }
}

Server Side

import java.awt.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;

class chatboxServer {
    JFrame fr;
    JPanel p;
    JTextArea ta;
    JButton send;
    ServerSocket ss;
    byte buffer[]=new byte[800];

    chatboxServer() {
        fr=new JFrame("ChatBox_SERVER");
        p=new JPanel();
        ta=new JTextArea();
        ta.setRows(20);
        ta.setColumns(20);
        send=new JButton("send");
        fr.add(p);
        p.add(ta);
        p.add(send);
        fr.setVisible(true);
        fr.setSize(500,500);
        fr.setResizable(false);

    }

    public void Receive(String sm) {
        try {
            buffer=sm.getBytes();
            InetAddress address=InetAddress.getLocalHost();
            DatagramSocket ds=new DatagramSocket(3000,address);
            DatagramPacket dp=new DatagramPacket(buffer,buffer.length);
            ds.receive(dp);
            String s=new String(dp.getData(),0,dp.getLength());
            ta.setText(s);  
        }    catch(Exception exc) {
            System.out.println("Error Receiving..");
        }
    }

    public void Laccept() {
        try {
            ss=new ServerSocket(3000);     // First making port number 3000 on server to listen
            Socket s=ss.accept();
        }   catch(Exception exc) {
            JOptionPane.showMessageDialog(new JFrame(),"Accept Failed :3000 :Server Side");
        }  
    }
}

PROBLEM---
Nothing happens when i click connect. What is the problem ?

One thing that i have checked :Program waits at ss.accept(); that is the reason i think the statement next to the call of Laccept() does not work...

Note that my aim through above code is to send message to the server,which is the same machine on which client is running

Please explain clearly as to what should i do ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

真心难拥有 2024-11-06 12:52:23

您首先必须决定是使用 TCP 还是 UDP 进行连接。

TCP 使用 Socket 和 ServerSocket 类,并为您提供一个连接,您可以通过该连接发送连续的字节流(也可以在另一个方向接收另一个字节流)。 TCP 协议确保所有数据以正确的顺序到达。

UDP 使用 DatagramSocket 类,并发送单独的包,这些包可能会也可能不会到达另一端(通常会到达,但不能保证,如果您自己不实现确认,则无法发现)。如果它们到达某个主机/端口并且没有进程在侦听,它们将被简单地丢弃。

通常,将两者混合在一起是没有意义的。


您的程序在同一线程中相继使用 UDP sendreceive,这将导致接收套接字没有机会读取它,因为数据包已被发送。已经扔掉了。您必须在发送包裹之前在单独的线程中调用 receive。


编辑(在发表评论后):

这就是 UDP 的工作方式。传入包裹没有队列。
ds.receive(dp); 调用等待从现在开始到达的新包,而不是等待过去某个时间发送的包。因此,这个调用将永远阻塞(并且另外在事件调度线程上,这意味着您不会得到任何重绘或其他事件处理)。

就像在新线程中启动 connect() 方法一样,也在新线程中启动服务器的 Receive 方法。 (事实上​​,你的服务器的 Laccept 没有用于任何用途。)

除此之外,你的两个 DatagramSocket(客户端一个和服务器一个)绑定到同一个本地端口,这也可能会导致问题。不要这样做。

You first have to decide whether you want to use TCP or UDP for your connection.

TCP uses the Socket and ServerSocket class, and gives you a connection, over which you can send a continuous stream of bytes (and receive another one in the other direction, too). The TCP protocol makes sure all the data arrives in the right order.

UDP uses the DatagramSocket class, and sends individual packages, which may or may not arrive at the other side (usually they do, but there is no guarantee, and you can't find out if you don't implement a confirmation yourself). If they arrive at some host/port and there is no process listening there, they will simply be discarded.

It is no point in mixing both, usually.


Your program uses UDP send and receive in the same thread one after another, which will have the effect that the receiving socket will have no chance to read it, since the packet was already thrown away. You have to call receive in a separate thread, and before sending the package.


Edit (after your comment):

This is the way UDP works. There is no queue for incoming packages.
The ds.receive(dp); call waits for new packages arriving from now on, not for packages which were sent sometime in the past. So this call will simply block forever (and additionally on the event dispatch thread, meaning you don't get any repaints or other event handling).

Like you start your connect() method in a new thread, also start the server's Receive method in a new thread. (In fact, your server's Laccept is not used for anything.)

Other than this, your two DatagramSockets (the client one and the server one) are bound to the same local port, which may also cause a problem. Don't do this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文