目录
  • 一、题目描述
  • 二、解题思路
  • 三、代码详解

一、题目描述

题目实现:在进行网络编程时,由于进行网络连接是比较消耗资源的,因此,可以对连接的等待时间进行设置,如果在规定的时间没有进行连接,则进行其他的处理。运行程序,等待10秒钟后,将弹出消息框提示连接超时。

二、解题思路

创建一个类:ConnectionTimeoutSetFrame,继承JFrame类

写一个getserver()方法,创建服务ServerSocket和设置等待超时时间。

原理是通过ServerSocket的实例对象,调用setSoTimeout()设置超时时间。

三、代码详解

ConnectionTimeoutSetFrame

package com.xiaoxuzhu;
import java.awt.BorderLayout;
import java.io.*;
import java.net.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
 * Description: 
 *
 * @author xiaoxuzhu
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本	        修改人		修改日期			修改内容
 * 2022/5/31.1	    xiaoxuzhu		2022/5/31		    Create
 * </pre>
 * @date 2022/5/31
 */
public class ConnectionTimeoutSetFrame extends JFrame {
    private JTextArea ta_info;
    private ServerSocket server; // 声明ServerSocket对象
    public void getserver() {
        try {
            server = new ServerSocket(9527); // 实例化Socket对象
            server.setSoTimeout(10000);// 设置连接超时时间为10秒
            ta_info.append("服务器套接字已经创建成功\n"); // 输出信息
            while (true) { // 如果套接字是连接状态
                ta_info.append("等待客户机的连接......\n"); // 输出信息
                server.accept();// 等待客户机连接
            }
        } catch (SocketTimeoutException e) {
            ta_info.append("连接超时......");
            JOptionPane.showMessageDialog(null, "连接超时......");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) { // 主方法
        ConnectionTimeoutSetFrame frame = new ConnectionTimeoutSetFrame(); // 创建本类对象
        frame.setVisible(true);
        frame.getserver(); // 调用方法
    }
    public ConnectionTimeoutSetFrame() {
        super();
        setTitle("设置等待连接的超时时间");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 336, 257);

        final JScrollPane scrollPane = new JScrollPane();
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        ta_info = new JTextArea();
        scrollPane.setViewportView(ta_info);
    }
}

10秒后,会提示连接超时。

Java聊天室之解决连接超时问题

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。