0
Follow
0
View

Java的套接字

heping8815 注册会员
2023-02-25 18:07

Refer to gpt and your own ideas, question 1: To pass the socket object in the connect button to the click event of the Start Monitor button, create a new SocketConnect object in the click event of the connect button and pass it as a parameter to the click event of the Start Monitor button. The implementation is as follows:


// 声明一个 SocketConnect 对象,在连接按钮点击事件中初始化
SocketConnect sc;

// 连接按钮点击事件中
btnconnect.addActionListener(new ActionListener(){   
    public void actionPerformed(ActionEvent e){
        // 创建新的 SocketConnect 对象,并传递 ip 地址
        sc = new SocketConnect(txtip.getText());
    }
});

// 开始监控按钮点击事件中,使用连接按钮中创建的 SocketConnect 对象
btnstart.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        // 判断是否已经建立连接
        if (sc == null || sc.socket == null || sc.socket.isClosed()) {
            // 如果未建立连接,提示用户建立连接
            System.out.println("请先建立连接");
        } else {
            // 如果已建立连接,执行发送数据的逻辑
            new Thread(new SendThread(sc.socket)).start();
        }
    }
});


In the above code, we create a new SocketConnect object in the click event of the connect button and assign it to a member variable named sc. In the click event of the start monitoring button, we determine whether a connection has been established by judging the value of sc variable. If the sc value is null, or the socket object in the sc value is null, or the socket is closed, the connection is not established and the user is prompted to establish a connection. Otherwise, a new thread is started to perform the logic to send the data.

Problem 2: To determine whether a connection has been established with the server for this IP address, you can add an isConnect() method to the SocketConnect class. The implementation is as follows:


public class SocketConnect implements Runnable{
    Socket socket;
    String ip;
    SocketConnect(String ip){
        this.ip=ip;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            socket = new Socket(ip,502);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public boolean isConnect() {
        return socket != null && socket.isConnected() && !socket.isClosed();
    }
}


In the above code, we add an isConnect() method that returns a boolean value indicating whether the current SocketConnect object has established a connection with the server at the specified IP. In the implementation, we determine the connection status by determining whether the socket is null, whether it has been connected and whether it has been closed. If true is returned, a connection has been established. Otherwise, the connection is not established.

Then, in the click event of the start Monitor button, you can call the isConnect() method of the SocketConnect object to determine whether a connection has been established. See the code in Question 1 for the specific implementation.

duanbo2001 注册会员
2023-02-25 18:07

Problem 1 can use arrays, defined outside the method

ct9501 注册会员
2023-02-25 18:07

Monster Group and GPt-based tuning:
Problem 1: You can pass the socket object as a parameter to the thread inside the start monitor button click event. For example, you can add a method to the SocketConnect class that takes a socket parameter and sets it as an instance variable of the class. You can then create a SocketConnect object in the click event of the connected button and pass it to the click event that starts monitoring the button.

Example:

public class SocketConnect implements Runnable{

    private Socket socket;
    private String ip;
    
    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    SocketConnect(String ip){
        this.ip=ip;
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            if (socket == null || socket.isClosed()) {
                socket = new Socket(ip,502);
            }
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


Then, in the connect button click event, you can create a new SocketConnect object and pass it to the start monitoring button click event. For example:

Socket socket = null;
btnconnect.addActionListener(new ActionListener(){   
    public void actionPerformed(ActionEvent e){
        if (socket == null || socket.isClosed()) {
            socket = new Socket();
            SocketConnect sc= new SocketConnect(txtip.getText());
            sc.setSocket(socket);
            Thread thread = new Thread(sc);
            thread.start();
        }
    }
});

btnstart.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if (socket != null && socket.isConnected()) {
            // 在此处发送数据
        }
    }
});


Problem 2: You can add a method to the SocketConnect class to check that the socket is connected to the server. For example:

public boolean isConnected() {
    return socket != null && socket.isConnected() && !socket.isClosed();
}



``
然后,在连接按钮的点击事件和开始监控按钮的点击事件中都可以调用该方法来检查socket是否已连接到服务器。例如:

btnconnect.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (socket == null || ! sc.isConnected()) {
socket = new Socket();
SocketConnect sc= new SocketConnect(txtip.getText());
sc.setSocket(socket);
Thread thread = new Thread(sc);
thread.start();
} else {
System.out.println(" Connected to server." );
}
}
});

btnstart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (socket ! = null & & sc.isConnected()) {
// Send data here
} else {
System.out.println(" Not connected to server." );
}
}
});

```

duyuan0516 注册会员
2023-02-25 18:07

the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > question 1: The socket object can be declared as a member variable of the JFrame class so that it can be accessed in the event of both button clicks, for example:

public class MyFrame extends JFrame{
    private Socket socket;
    private JTextField ip;
    //...
    
    public MyFrame(){
        //...
        JButton btnconnect = new JButton("连接");
        btnconnect.addActionListener(new ActionListener(){   
            public void actionPerformed(ActionEvent e){
                connectToServer(txtip.getText());
            }
        });
        
        JButton btnstart = new JButton("开始监控");
        btnstart.addActionListener(new ActionListener(){   
            public void actionPerformed(ActionEvent e){
                sendDataToServer();
            }
        });
    }
    
    private void connectToServer(String ip){
        if(socket != null && socket.isConnected()){
            System.out.println("已经与该IP的Server建立了连接");
            return;
        }
        try {
            socket = new Socket(ip,502);
            System.out.println("已经与该IP的Server建立了连接");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private void sendDataToServer(){
        if(socket == null || !socket.isConnected()){
            System.out.println("还未与该IP的Server建立连接,请先连接");
            return;
        }
        //开始发送数据
    }
}


Problem 2: In the connectToServer method, the isConnected method of the socket object determines whether a connection has been established with the Server. If the connection has been established, the connection is directly returned. Otherwise, the connection is established.

About the Author

Question Info

Publish Time
2023-02-25 18:07
Update Time
2023-02-25 18:07