Java autoflush TCP / IP服务器

时间:2016-08-29 14:02:19

标签: java sockets tcp

大家好抱歉打扰每个人,我需要在Netbeans for TCP / IP Server上进行一些帮助编码,问题是我得到的实现是创建套接字但是我使用TCP / IP Builder Application来测试我的程序

当我尝试接收某些数据时,问题就出现了,因为TCP / IP Builder需要关闭套接字才能刷新Netbeans应用,请帮助我(



Declare

Type my_record is record(
    CUST_ID   number(7);
    CUST_NAME varchar2(200);
);

my_var my_record ;
my_new_var my_var.CUST_NAME%type;
begin
null;
end;






package my.protinterface;
import java.awt.Image;
import javax.swing.ImageIcon;
import java.sql.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mauricio_gonzalez
 */
public class PROTInterface extends javax.swing.JFrame {

    /**
     * Creates new form PROTInterface
     */
    public PROTInterface() {
        initComponents();
    }
    
    //FRAME LOGO
    Image img =(new ImageIcon(getClass().getResource("logo.png"))).getImage();
    
    //SQL
    Connection con;
    
    //TCP/IP
    public static ArrayList clientOutputStreams;
    public static ArrayList<String> users;
    
    //Classes
    protocols.SQLConnection sqlconnection = new protocols.SQLConnection();
    protocols.TCP_IP tcp_ip = new protocols.TCP_IP();
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        Label_Protocols1 = new javax.swing.JLabel();
        Label_Protocols2 = new javax.swing.JLabel();
        ComboBox_Protocols_Protocol = new javax.swing.JComboBox();
        ComboBox_Protocols_Port = new javax.swing.JComboBox();
        Button_Protocols_Start = new javax.swing.JButton();
        Button_Protocols_Clean = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        ComboBox_Database_Name = new javax.swing.JComboBox();
        ComboBox_Database_Field = new javax.swing.JComboBox();
        Label_Database1 = new javax.swing.JLabel();
        Label_Database2 = new javax.swing.JLabel();
        Button_Database_Connect = new javax.swing.JButton();
        Button_Database_Test = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        TextArea_Protocols = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        TextArea_Database = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Smart Manufacturing Interface");
        setIconImage(img);
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Protocols"));

        Label_Protocols1.setText("Protocol");

        Label_Protocols2.setText("Port");

        ComboBox_Protocols_Protocol.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "OPC-UA", "TCP/IP", "UDP" }));

        ComboBox_Protocols_Port.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "7171", "7172" }));

        Button_Protocols_Start.setText("Start Server");
        Button_Protocols_Start.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Button_Protocols_StartActionPerformed(evt);
            }
        });

        Button_Protocols_Clean.setText("Clean Record");
        Button_Protocols_Clean.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Button_Protocols_CleanActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(Label_Protocols1)
                            .addComponent(Label_Protocols2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(ComboBox_Protocols_Port, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(ComboBox_Protocols_Protocol, 0, 130, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(Button_Protocols_Clean)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(Button_Protocols_Start)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Label_Protocols1)
                    .addComponent(ComboBox_Protocols_Protocol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Label_Protocols2)
                    .addComponent(ComboBox_Protocols_Port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Button_Protocols_Start)
                    .addComponent(Button_Protocols_Clean)))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Database"));
        jPanel2.setPreferredSize(new java.awt.Dimension(267, 152));

        ComboBox_Database_Name.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "ADA", "Smart_Manufacturing" }));

        ComboBox_Database_Field.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All", "User Level", "Name", "User Name", "Email", "Employee Number", "Job Title", "MAC", "PC Active", "LAP Active", "Cellphone", "Birthday", "Shoes Number", "Admission Date" }));

        Label_Database1.setText("Database");

        Label_Database2.setText("Field");

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

        Button_Database_Test.setText("Test");
        Button_Database_Test.setEnabled(false);
        Button_Database_Test.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Button_Database_TestActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(Label_Database2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(ComboBox_Database_Field, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(Label_Database1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(Button_Database_Test, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ComboBox_Database_Name, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Button_Database_Connect, javax.swing.GroupLayout.Alignment.TRAILING)))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ComboBox_Database_Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Label_Database1))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ComboBox_Database_Field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Label_Database2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Button_Database_Connect)
                    .addComponent(Button_Database_Test)))
        );

        TextArea_Protocols.setEditable(false);
        TextArea_Protocols.setColumns(20);
        TextArea_Protocols.setLineWrap(true);
        TextArea_Protocols.setRows(5);
        TextArea_Protocols.setToolTipText("Text generated by communicated devices");
        TextArea_Protocols.setSelectionColor(new java.awt.Color(255, 102, 102));
        jScrollPane1.setViewportView(TextArea_Protocols);

        TextArea_Database.setEditable(false);
        TextArea_Database.setColumns(20);
        TextArea_Database.setLineWrap(true);
        TextArea_Database.setRows(5);
        TextArea_Database.setToolTipText("Text generated by Database connection actions");
        TextArea_Database.setSelectionColor(new java.awt.Color(255, 102, 102));
        jScrollPane2.setViewportView(TextArea_Database);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

    private void Button_Database_ConnectActionPerformed(java.awt.event.ActionEvent evt) {                                                        
        try {
            con = sqlconnection.doDatabaseConnection(ComboBox_Database_Name.getSelectedItem().toString());
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(PROTInterface.class.getName()).log(Level.SEVERE, null, ex);
        }
        Button_Database_Test.setEnabled(true);
    }                                                       

    private void Button_Database_TestActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        String textbuffer = "";
        try {
            textbuffer = sqlconnection.getDatabaseTest(con,ComboBox_Database_Field.getSelectedItem().toString());
        } catch (SQLException ex) {
            Logger.getLogger(PROTInterface.class.getName()).log(Level.SEVERE, null, ex);
        }
        if(!"".equals(textbuffer))
            TextArea_Database.setText(textbuffer);
        else
            TextArea_Database.setText("No Textbuffer");
    }                                                    

    private void Button_Protocols_CleanActionPerformed(java.awt.event.ActionEvent evt) {                                                       
        TextArea_Protocols.setText("");
    }                                                      

    private void Button_Protocols_StartActionPerformed(java.awt.event.ActionEvent evt) {                                                       
        if("Start Server".equals(Button_Protocols_Start.getText())){
            if("TCP/IP".equals(ComboBox_Protocols_Protocol.getSelectedItem())){
                Thread starter = new Thread(new ServerStart());
                starter.start();
                TextArea_Protocols.append("Server started...\n");
                
                ComboBox_Protocols_Protocol.setEnabled(false);
                ComboBox_Protocols_Port.setEnabled(false);
                Button_Protocols_Start.setText("End Server");
            }
        }
        else if("End Server".equals(Button_Protocols_Start.getText())){
            if("TCP/IP".equals(ComboBox_Protocols_Protocol.getSelectedItem())){
                tcp_ip.tellEveryone("Server:is stopping and all users will be disconnected.\n:Chat", TextArea_Protocols);
                TextArea_Protocols.append("Server stopping... \n");
                try 
                {
                    Thread.sleep(5000);                 //5000 milliseconds is five second.
                } 
                catch(InterruptedException ex) {Thread.currentThread().interrupt();}
                TextArea_Protocols.setText("");
                
                ComboBox_Protocols_Protocol.setEnabled(true);
                ComboBox_Protocols_Port.setEnabled(true);
                Button_Protocols_Start.setText("Start Server");
            }            
        }
    }                                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PROTInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PROTInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PROTInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PROTInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PROTInterface().setVisible(true);
            }
        });
    }
    
    //TCP/IP
    public class ClientHandler implements Runnable{
        BufferedReader reader;
        Socket sock;
        PrintWriter client;

        public ClientHandler(Socket clientSocket, PrintWriter user) {
            client = user;
            try 
            {
                sock = clientSocket;
                InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
                reader = new BufferedReader(isReader);
            }
            catch (Exception ex) 
            {
                TextArea_Protocols.append("Unexpected error... \n");
            }
        }

        public void run() {
            String message, connect = "Connect", disconnect = "Disconnect", chat = "Chat" ;
            String[] data;

            try
            {
                while ((message = reader.readLine()) != null){
                    TextArea_Protocols.append("Received: " + message + "\n");
                    data = message.split(":");
                    
                    for (String token:data) 
                    {
                        TextArea_Protocols.append(token + "\n");
                    }

                    if (data[2].equals(connect)) 
                    {
                        tcp_ip.tellEveryone((data[0] + ":" + data[1] + ":" + chat), TextArea_Protocols);
                        tcp_ip.userAdd(data[0], TextArea_Protocols);
                    } 
                    else if (data[2].equals(disconnect)) 
                    {
                        tcp_ip.tellEveryone((data[0] + ":has disconnected." + ":" + chat), TextArea_Protocols);
                        tcp_ip.userRemove(data[0], TextArea_Protocols);
                    } 
                    else if (data[2].equals(chat)) 
                    {
                        tcp_ip.tellEveryone(message, TextArea_Protocols);
                    } 
                    else 
                    {
                        TextArea_Protocols.append("No Conditions were met. \n");
                    }
                }
            }
            catch (Exception ex) 
            {
               TextArea_Protocols.append("Lost a connection. \n");
               //ex.printStackTrace();
               clientOutputStreams.remove(client);
            }
	} 
    }
    
    public class ServerStart implements Runnable {
        @Override
        public void run() 
        {
            clientOutputStreams = new ArrayList();
            users = new ArrayList();  

            try 
            {
                ServerSocket serverSock = new ServerSocket(Integer.parseInt(ComboBox_Protocols_Port.getSelectedItem().toString()));

                while (true)
                {
                    Socket clientSock = serverSock.accept();
                    PrintWriter writer = new PrintWriter(clientSock.getOutputStream());
                    clientOutputStreams.add(writer);
                    
                    Thread listener = new Thread(new ClientHandler(clientSock, writer));
                    listener.start();
                    TextArea_Protocols.append("Got a connection. \n");
                }
            }
            catch (NumberFormatException | IOException ex)
            {
                TextArea_Protocols.append("Error making a connection. \n");
            }
        }
    }
    //TCP/IP
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:-1)

*解决

经过一天的调查和努力工作:)我发现问题根本不是java的代码。

关键是以下内容!

  

BufferedReader.readLine()

结果比BufferedReader有的methode readLine仅在缓冲区中发送了回车或通常称为\ r \ n时读取

无论如何我使用的程序是 TCP / IP Builder rev 1.9 ,但我发送的数据没有\ r \ n,在这个程序中你没有选择添加ASCII代码。

我使用Hercules解决了这个问题并测试了TCP通信,这很有效!

  

BufferReader.read()

.read()不需要\ r \ n但是它返回char的代码char,try catch语句不要让我包括这个选项。

奖励,我希望它对任何人都有用。

注意:

  

并非TCP / IP的所有通信外部程序都需要通过TCP进行\ r或\ n通信,这是.readList()Java函数的特殊例外。