简体   繁体   English

单击“连接”时什么也没发生

[英]Nothing Happens When I Click Connect

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(); 我检查过的一件事: 程序在ss.accept()中等待; that is the reason i think the statement next to the call of Laccept() does not work... 这就是我认为Laccept()调用旁边的语句不起作用的原因...

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 ? 请清楚说明我该怎么办?

You first have to decide whether you want to use TCP or UDP for your connection. 您首先必须确定是要使用TCP还是UDP进行连接。

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). TCP使用Socket和ServerSocket类,并为您提供连接,通过该连接您可以发送连续的字节流(也可以从另一个方向接收另一个字节流)。 The TCP protocol makes sure all the data arrives in the right order. TCP协议确保所有数据以正确的顺序到达。

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). UDP使用DatagramSocket类,并发送单独的程序包,该程序包可能到达或可能不到达另一端(通常它们可以到达,但不能保证,并且您无法确定自己是否未实现确认)。 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. 您的程序在同一线程中一个接一个地使用UDP sendreceive ,这将导致接收套接字没有机会读取它,因为包已经被丢弃了。 You have to call receive in a separate thread, and before sending the package. 您必须在发送包之前在单独的线程中调用receive。


Edit (after your comment): 编辑(在您的评论后):

This is the way UDP works. 这就是UDP的工作方式。 There is no queue for incoming packages. 没有传入软件包的队列。 The ds.receive(dp); ds.receive(dp); call waits for new packages arriving from now on, not for packages which were sent sometime in the past. call等待从现在开始到达的新包,而不是等待过去某个时间发送的包。 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. 就像在新线程中启动connect()方法一样,也在新线程中启动服务器的Receive方法。 (In fact, your server's Laccept is not used for anything.) (实际上,服务器的Laccept不会用于任何用途。)

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. 除此之外,您的两个DatagramSocket(客户端一个和服务器一个)绑定到同一本地端口,这也可能会引起问题。 Don't do this. 不要这样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM