我正在尝试使用演示WiFi直接应用程序直接与wifi建立客户端服务器套接字连接。演示应用程序在活动打开时建立连接的情况下工作正常但是 如果我创建后台服务并尝试侦听套接字连接,则后台服务中运行的服务器不接受连接。 代码如下:
Server:
public class MyBackgroundService extends Service implements ChannelListener, ConnectionInfoListener {
private Runnable runnable = new Runnable() {
@Override
public void run() {
// put your socket-code here
String filename= null;
// Toast t = Toast.makeText(context,"Opening a server socket",Toast.LENGTH_LONG);
// t.show();
DataInputStream inputstream = null;
try {
ServerSocket serverSocket = new ServerSocket(8988);
Log.e(WiFiDirectActivity.TAG, "Server: Socket opened");
Socket client = serverSocket.accept();
Log.e(WiFiDirectActivity.TAG, "Server: connection done");
....
}
@Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
this.info = info;
if (info.groupFormed && info.isGroupOwner) {
Log.e(WiFiDirectActivity.TAG,"FileServeronConneitoninfo Background");
new Thread(runnable).start();
}
}
客户端:
public class FileTransferService extends IntentService {
private static final int SOCKET_TIMEOUT = 0;
@Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String filename= intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
DataOutputStream stream = null;
try {
Log.e(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.bind(null);
Log.e(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Log.e(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
// ...
}
catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, "IOException in File transfer");
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
stream.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
客户端正在获得超时异常,并且connect和accept之后的两行都没有执行。有什么可能的原因吗? 我已将超时0设置为防止超时异常,但仍然没有建立连接。这只发生在后台服务中,但如果我在活动中这样做,一切正常。 提前谢谢。
Log Cat服务器端输出:
01-28 11:21:12.391 E / wifidirectdemo:COnnection_Change_BackgroundService
01-28 11:21:12.392 E / wifidirectdemo:ConnectionInfo可用背景
01-28 11:21:12.392 E / wifidirectdemo:FileServeronConneitoninfo背景
01-28 11:21:12.394 E / wifidirectdemo:服务器:套接字打开
01-28 11:21:22.877 E / wifidirectdemo:P2P对等体发生了变化