简体   繁体   中英

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(); 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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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