我正在使用wifi direct在两个移动设备之间进行通信。我有安装套接字来发送和接收消息。如果我先启动服务器设备(所有者),然后再启动客户端设备(成员),则一切正常。我想以任何顺序启动任何设备,但仍然设法发送消息。
当前,客户端等待5秒钟,如果没有可用的连接,则它将停止寻找服务器。我希望客户端即使在超时后仍继续寻找服务器,直到找到服务器连接为止。我已尝试执行此操作,但尚未成功实现。
初始客户代码:
@Override
public void run() {
Socket socket = new Socket();
try {
socket.bind(null);
socket.connect(new InetSocketAddress(address.getHostAddress(), SERVER_PORT), TIME_OUT);
socketCreator = new SocketCreator(socket, handler);
new Thread(socketCreator).start();
} catch (IOException e) {
e.printStackTrace();
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return;
}
}
修改如下:
@Override
public void run() {
Socket socket = new Socket();
try {
socket.setReuseAddress(true);
socket.bind(null);
while(!connectedToServer) {
try {
socket.connect(new InetSocketAddress(address.getHostAddress(), SERVER_PORT),
TIME_OUT);
socketCreator = new SocketReadWriter(socket, handler);
new Thread(socketCreator).start();
connectedToServer = true;
} catch (ConnectException e) {
Log.i(TAG,"Error while connecting. " + e.getMessage());
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} catch (Exception e){
Log.i(TAG,"Exception "+e.getMessage());
}
}
} catch (IOException e) {
e.printStackTrace();
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
我的代码中缺少什么?我该如何运作?
我不断收到此错误:
Exception java.io.IOException: fcntl failed: EBADF (Bad file number)
您必须new Socket()
每次创建一个。无法连接到远程服务器会使套接字无效,无法进一步使用。
如果connect()失败,则将套接字的状态视为未指定。便携式应用程序应关闭插座并创建一个新插座以重新连接。http://man7.org/linux/man-pages/man2/connect.2.html
由于您是在Android上运行此程序-我猜您在尝试调用connect
两次时未看到“套接字关闭”错误。
@Override
public void run()
{
connector: while (true)
{
Socket socket = new Socket();
try
{
socket.connect(new InetSocketAddress("0.0.0.0", 9999), 2000);
this.doSomethingElseWithConnectedSocket(socket);
break connector; // break out of the while loop
}
catch (ConnectException e)
{
// ignore because worthless
}
try
{
socket.close();
}
catch(Throwable x)
{
// ignore
}
System.out.println("Unable to connect to server ");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e1)
{
// ignore
}
}
}
public void doSomethingElseWithConnectedSocket(Socket value)
{
value.close(); // close for no good reason
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句