发送到服务器套接字超时
public void sendToServer(String fileToSend, String ip, int sendPort)
{
int port = sendPort;
String url = ip;
File file = new File(fileToSend);
String fileName = file.getName();
Socket sock;
try {
sock = new Socket(url,port);
//Send the file name
OutputStream socketStream = sock.getOutputStream();
ObjectOutput objectOutput = new ObjectOutputStream(socketStream);
objectOutput.writeObject(fileName);
//Send File
byte [] mybytearray = new byte [(int)file.length()];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
fileSentOkay();
os.flush();
sock.close();
} catch (UnknownHostException e) {
hostNotFound();
} catch (IOException e) {
hostNotFound();
}
}
当我尝试在服务器未侦听连接时向服务器发送某些内容时,手机会不断尝试发送文件。因此,我的 Android 程序最终将被强制关闭。
我怎样才能为这件事设定一个时间呢?我是否必须在发送数据的套接字上使用类似 setSoTimeout()
的东西?
public void sendToServer(String fileToSend, String ip, int sendPort)
{
int port = sendPort;
String url = ip;
File file = new File(fileToSend);
String fileName = file.getName();
Socket sock;
try {
sock = new Socket(url,port);
//Send the file name
OutputStream socketStream = sock.getOutputStream();
ObjectOutput objectOutput = new ObjectOutputStream(socketStream);
objectOutput.writeObject(fileName);
//Send File
byte [] mybytearray = new byte [(int)file.length()];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
fileSentOkay();
os.flush();
sock.close();
} catch (UnknownHostException e) {
hostNotFound();
} catch (IOException e) {
hostNotFound();
}
}
When I try to send something to the server when the server isn't listening for the connection, the phone keeps attempting to send the file. As a result of this, my Android program will eventually force close.
How could I set a time out for this to happen? Would I have to use something like setSoTimeout()
on the socket that is sending the data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一:以防万一:不要在 UI 线程上执行网络操作。不好的事情会发生(tm)
第二:
setSoTimeout()
应该给你一个超时,以防服务器接受连接,但不回复(或者根本没有来自网络的回复) 。如果连接被拒绝,套接字的失败速度应该会更快。编辑:如果 Socket 类的构造函数已经花费了那么长时间,请尝试使用
connect(SocketAddress, int)
方法。使用 InetSocketAddress 作为参数:First: Just in case: Don't do network stuff on the UI Thread. Bad Things will happen (tm)
Second:
setSoTimeout()
should give you a timeout in case the server accepts the connection, but does not reply (or in case there is no reply from the network at all). In case the connection is rejected the socket should fail significantly faster.Edit: In case the constructor of the Socket class is already taking that long, try using the
connect(SocketAddress, int)
method. Use InetSocketAddress as parameter: