2

**这是两个同行之间聊天的简单代码。据我说,代码做了它应该做的,但我在解决这个 SocketException 错误时遇到了困难。在我进行最后一次修改之前,这段代码运行良好。现在我发现很难追踪错误。

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import java.net.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class UDPchat extends Thread implements ActionListener
{
    JFrame f;
    JPanel p;
    JTextField text;
    JButton b;
    JTextArea ta;
    private final static String newline = "\n";
    private final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    int porttor=7777; // port to send/receive datagrams on
    //int porttos=5555;
    String remoteIPaddress= ("127.0.0.1");      // IP to send datagrams

    public UDPchat() throws Exception
    {
        start();      // start thread to receive and display datagrams
        f=new JFrame("CHAT WINDOW");
        p= new JPanel();
        text = new JTextField();
        text.setColumns(25);

        b = new JButton("SEND");

        b.addActionListener(this);

        ta = new JTextArea("Chat messages",20,50);

        ta.setEditable(false);

        f.setLayout(new FlowLayout());

        p.add(text,BorderLayout.NORTH);

        p.add(b,BorderLayout.SOUTH);

        f.setLayout(new BorderLayout());

        f.add(ta,BorderLayout.NORTH);

        f.add(p,BorderLayout.SOUTH);

        f.setSize(400, 400);

        f.setVisible(true);
    }

    @Override

    public void actionPerformed(ActionEvent e)
    {

        try
        {

            String s = text.getText();  // read a String

            text.setText(" ");

            ta.append(newline);

            ta.append(s);

            //System.out.println("Sending to " + remoteIPaddress + " socket " + port + " data: " + s);

            byte[] data = s.getBytes();  // convert to byte array

            DatagramSocket theSocket = new DatagramSocket();  // create datagram socket and the datagram

            DatagramPacket   theOutput = new DatagramPacket(data, data.length, InetAddress.getLocalHost(), 5555);

            theSocket.send(theOutput);     

        }

        catch(Exception et)
        {

            System.out.println("Error sending datagram" + et);

        }

    }

    // thread run method, receives datagram and display contents as a string
    public void run()                
    {

        try
        {

            // open DatagramSocket to receive 

            DatagramSocket ds = new DatagramSocket(7777);

            // loop forever reading datagrams from the DatagramSocket

            while (true)
            {

                byte[] buffer = new byte[65507];  // array to put datagrams in

                DatagramPacket dp = new DatagramPacket(buffer, buffer.length);  // DatagramPacket to hold the datagram

                try {

                    ds.receive(dp);

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    System.err.println("chat error2 " + e);

                }   // wait for next datagram

                String s = new String(dp.getData(),0,dp.getLength()); // get contents as a String

                System.out.println("UDP datagram length " + s.length()+ "  from IP " + dp.getAddress() + " received: " + s );

                ta.append(newline);

                ta.append(s);

            }

        }

        catch (SocketException se)
        {

             System.err.println("chat error1 " + se);

        }

        //catch (IOException se) {System.err.println("chat error2 " + se);}

        //System.exit(1);   // exit on error

    }

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

        UDPchat c=new UDPchat();

    }

}
4

2 回答 2

1

你确定有其他应用程序绑定到该端口(7777)吗?您是否尝试过具有相同结果的其他端口?

并且请确保没有运行杀毒软件或防火墙,这也可以拒绝绑定到端口。

于 2012-01-01T08:46:46.710 回答
1

检查您在代码中制作两种类型的 DatagramSocket,尝试提供相同的 7777 端口。您的 actionPerformed() 方法中的一个为:

DatagramSocket theSocket = new DatagramSocket();  // create datagram socket and the datagram

和你的运行方法中的一个:

// open DatagramSocket to receive 

DatagramSocket ds = new DatagramSocket(7777);

Upper 构造函数正在创建一个数据报套接字并将其绑定到本地主机上的任何可用端口,第二个构造函数试图到达端口 7777。尝试用相同的端口号初始化两者,这将为您解决问题。

希望这可能会有所帮助。

问候

于 2012-01-01T11:43:43.663 回答