基于Netbeans的简单客户/服务器套接字

时间:2014-03-28 18:40:14

标签: java sockets netbeans client

我是初学者,我在netbeans中编写了一个简单的客户端服务器套接字模型 - 服务器是一个简单的列表在端口1119上,并从客户端接收消息并打印它们(控制台模块)。 - 客户端基于netbeans Form模型,并具有文本字段和两个按钮(连接和发送),如图所示:

http://s24.postimg.org/on6svgjpx/sss.jpg

我应该按连接一次,然后当我在文本字段中键入消息并按发送它发送到服务器应该打印好了,现在它开始工作,但之后它没有发送任何东西,我需要再次按连接发送它,我想要的东西是让客户端按一次连接只有一次,之后我可以发送消息,当按发送不再使用连接!!!!所以请帮我怎么做!

这是简单的代码:

import java.net.*;
import java.io.*;

public class Server {


   public static void main(String args []) throws IOException
    {
      System.out.println("Starting Server ....");
       ServerSocket ss=new ServerSocket(1119);
       while(true){
       Socket connection=ss.accept();
    DataOutputStream dout=new DataOutputStream(connection.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
String s=br.readLine();
System.out.println(s+"\n");
        }
   }
}

客户端代码(它是netbeans IDE):

import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class test extends javax.swing.JFrame {
DataOutputStream dout;
BufferedReader br;
Socket cs=null;
    /** Creates new form test */
    public test() {
        initComponents();
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Send");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Connect");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(288, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(39, 39, 39))
            .addGroup(layout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(86, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(22, 22, 22))
        );

        pack();
    }// </editor-fold>

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            cs = new Socket("127.0.0.1", 1119);
            dout=new DataOutputStream(cs.getOutputStream());

            // TODO add your handling code here:
        } catch (UnknownHostException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            dout.writeBytes(jTextField1.getText()+"\n");
            // TODO add your handling code here:
        } catch (IOException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new test().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration

}

1 个答案:

答案 0 :(得分:0)

我想要的是让客户端连接一次只能连接一次,之后我可以在按下发送时不再使用连接发送消息!

改变这个:

while(true){
       Socket connection=ss.accept();//here
       DataOutputStream dout=new DataOutputStream(connection.getOutputStream());
       BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
       String s=br.readLine();
       System.out.println(s+"\n");
}

要:

Socket connection=ss.accept();//here
while(true){
    DataOutputStream dout=new DataOutputStream(connection.getOutputStream());
    BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String s=br.readLine();
    System.out.println(s+"\n");
        }

在forever循环中保持accept()将使服务器等待新的连接。