创建新Socket时添加超时 [英] Add a timeout when creating a new Socket

查看:156
本文介绍了创建新Socket时添加超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有DHCP和一些PC的本地网络。其中一个应该是我的服务器并自动连接到所有其他(客户端)。我的想法是这样的:
首先,我在每个客户端(CServer)上创建一个服务器,它从服务器(SClient)监听客户端程序。当SClient连接到CServer时,SClient向CServer发送他的IP,因此他知道该IP上将有服务器。然后在尝试IP范围内的所有IP(例如192.168.1.xxx)后,他启动真实服务器并且所有客户端连接到已知服务器IP。
但是当我尝试以下操作时,SClient在尝试连接到192.168.1.0时只在第一个IP冻结。我如何定义超时或类似的东西,让SClient丢弃不成功的连接并继续使用192.168.1.1?

I have a local network with DHCP and a few PCs. One of these should be my Server and get automatically connected to all others (clients). My idea was this: First, I create a server on every client (CServer) that is listening for a client programm from the server (SClient). When the SClient connects to a CServer, the SClient sends the CServer his IP, so he knows there will be the server on this IP. Then after trying all IPs in his IP range (e.g. 192.168.1.xxx), he starts the real server and all the clients connect to the known server IP. But when I try the following, the SClient just freezes at the first IP, when trying to connect to 192.168.1.0. How can i define a timeout or something similar that lets the SClient drop the unsuccessful connection and going on with 192.168.1.1?

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

class SClient {
    public SClient() {
        for(int i = 120; i < 125; i++){
            try{
                InetAddress addr = InetAddress.getLocalHost();
                String addrs = addr+"";
                String ip = addrs.substring(addrs.indexOf("/")+1);
                Socket s1 = new Socket("192.168.1." + i, 1254);

                OutputStream s1out = s1.getOutputStream();
                DataOutputStream dos = new DataOutputStream (s1out);
                dos.writeUTF(ip);
                dos.close();
                s1out.close();
                s1.close();
            }catch(IOException e){}
        }
    }
}

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

class CServer {
    public CServer() throws IOException{
        ServerSocket s = new ServerSocket(1254);

        while(true){
            Socket s1=s.accept();
            InputStream s1In = s1.getInputStream();
            DataInputStream dis = new DataInputStream(s1In);
            String st = new String (dis.readUTF());
            System.out.println(st);
            dis.close();
            s1In.close();
            s1.close();
    }
}

}

推荐答案

我找到了解决问题的方法。它只是初始化Socket而不是

I've found a solution for my problem. It was just initializing the Socket not with

Socket s1 = new Socket("192.168.1." + i, 1254);

但是

Socket s1 = new Socket();
s1.setSoTimeout(200);
s1.connect(new InetSocketAddress("192.168.1." + i, 1254), 200);

无论如何,谢谢!

这篇关于创建新Socket时添加超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆