1
class SomeUI     
{ 
SocketMessageSender messageSender; 
// ensure that its initialized ... 
private void bSendMessageActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            // TODO add your handling code here:
            messageSender.sendMessage(jMessage.getText()); 
            jMessage.setText("");
        } catch (IOException ex) {
            Logger.getLogger(TeKServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 
}

错误:线程“AWT-EventQueue-0”中的异常 java.lang.RuntimeException:无法编译的源代码 - 错误的 sym 类型:bSendMessageActionPerformed

4

2 回答 2

1

为什么每次单击按钮时都要打开套接字并关闭它。创建一个类,允许您在应用程序运行期间保持套接字打开。应用启动时就可以进行socket连接了,可以试试下面的类

public class SocketMessageSender
{
    private String host;
    private int port;
    private DataOutputStream dos;

    public SocketMessageSender(String host, int port)
    {
        this.host = host;
        this.port = port;
    }

    // call when application starts
    public void initConnection() throws IOException
    {
        InetAddress address = InetAddress.getByName(host);
        Socket connection = new Socket(address, port);
        dos = new DataOutputStream(connection.getOutputStream());
    }

    //call from button click
    public void sendMessage(String message) throws IOException
    {
        if(dos != null)
        {
            dos.writeUTF(message);
            dos.flush();
        }
    }

    // call when application exits
    public void closeConnection() throws IOException
    {
        if(dos!= null)
        {
            dos.close();
        }
    }
}

希望能帮助到你 ...

假设你有一个像

class SomeUI
{
   SocketMessageSender messageSender;
   // ensure that its initialized ...



 private void bSendMessageActionPerformed(java.awt.event.ActionEvent evt) {
    messageSender.sendMessage(jMessage.getText());
    jMessage.setText("");
 }
}

我认为类签名应该是这样的......

public class MyPanel extends JPanel implements ActionListener
{
    private SocketMessageSender messageSender;
    private Message jMessage = new Message();// This is just a temp class, replace this with your class

    public MyPanel()
    {
        messageSender = new SocketMessageSender("some host", 8080);
        try
        {
            messageSender.initConnection();
        }
        catch(IOException e)
        {
             Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        try {
            // TODO add your handling code here:
            messageSender.sendMessage(jMessage.getText()); 
            jMessage.setText("");
        } catch (IOException ex) {
            Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
于 2012-09-22T12:02:54.740 回答
0

考虑使用 ObjectOutputStream/ObjectInputStream 并通过套接字写入对象。java2s.com 上有很多例子

请注意,如果您多次写入同一个对象,则需要在写入之前 reset() 流,并在之后刷新。

于 2012-09-22T10:16:47.200 回答