我正面临线程和套接字的问题,我无法弄清楚,如果有人可以帮助我,我将不胜感激。
有以下事实:
我有一个服务类 NetworkService,在这个类中我有一个 Socket 属性。我希望它在服务的整个生命周期内都处于连接状态。
为了连接套接字,我在一个线程中完成,所以如果服务器必须超时,它不会阻塞我的 UI 线程。
问题是,在我连接我的套接字的线程中一切都很好,它已连接并且我可以与我的服务器交谈,一旦这个线程结束并且我尝试重用套接字,在另一个线程中,我有错误消息Socket is not connected
。
问题是: - 套接字是否在线程结束时自动断开?- 他们无论如何我们可以将一个值从被调用线程传回给调用者吗?
非常感谢,
这是我的代码
public class NetworkService extends Service {
private Socket mSocket = new Socket();
private void _connectSocket(String addr, int port) {
Runnable connect = new connectSocket(this.mSocket, addr, port);
new Thread(connect).start();
}
private void _authentification() {
Runnable auth = new authentification();
new Thread(auth).start();
}
private INetwork.Stub mBinder = new INetwork.Stub() {
@Override
public int doConnect(String addr, int port) throws RemoteException {
_connectSocket(addr, port);
_authentification();
return 0;
}
};
class connectSocket implements Runnable {
String addrSocket;
int portSocket;
int TIMEOUT=5000;
public connectSocket(String addr, int port) {
addrSocket = addr;
portSocket = port;
}
@Override
public void run() {
SocketAddress socketAddress = new InetSocketAddress(addrSocket, portSocket);
try {
mSocket.connect(socketAddress, TIMEOUT);
PrintWriter out = new PrintWriter(mSocket.getOutputStream(), true);
out.println("test42");
Log.i("connectSocket()", "Connection Succesful");
} catch (IOException e) {
Log.e("connectSocket()", e.getMessage());
e.printStackTrace();
}
}
}
class authentification implements Runnable {
private String constructFirstConnectQuery() {
String query = "toto";
return query;
}
@Override
public void run() {
BufferedReader in;
PrintWriter out;
String line = "";
try {
in = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
out = new PrintWriter(mSocket.getOutputStream(), true);
out.println(constructFirstConnectQuery());
while (mSocket.isConnected()) {
line = in.readLine();
Log.e("LINE", "[Current]- " + line);
}
}
catch (IOException e) {e.printStackTrace();}
}
}