我想在我的服务器和客户端之间创建套接字连接 . 在连接超时后,我的客户端应该重新连接 . 为此,我每隔3秒尝试连接一次插座 . 这很有效 . 但是,当我想开始阅读,但后来我得到错误“套接字关闭” . 可能是什么错误?
这是错误日志(它在pastebin上,它在这里没有合成):
但是在我开始阅读之前,我尝试从套接字中获取IP,这有效......
这是我的重新连接方法:
public void reconnect(){
new Thread(new Runnable() {
@Override
public void run() {
try{
try{
socket.close();
socket = null;
}catch (IOException e) {
}
socket = new Socket(BackgroundService.HOSTNAME, BackgroundService.PORT);
connected = true;
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeUTF(username);
output.flush();
}catch(UnknownHostException e){
connected = false;
}catch(IOException e){
connected = false;
}
}
}).start();
}
在这里我等待输入:
public Notification waitForNotification(){
try{
if(!(connected))return null;
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
String input;
Log.e("Before Input", socket.getInetAddress()+"");
while((input = inputStream.readUTF()) != null){
Notification notification = new Notification(input);
return notification;
}
return null;
} catch (IOException e) {
e.printStackTrace();
Log.e("Lost Connection3", "ERROR");
connected = false;
return null;
}
}
在这里我管理它:
@Override
protected void onHandleIntent(Intent intent) {
Log.e("HII", "HII");
username = getDataFromStorage.loginData(getApplicationContext())[0];
new Thread(new Runnable() {
@Override
public void run() {
ConnectionService connectionService = new ConnectionService(username);
while (true) {
if(!(connectionService.getConnectionState())){
try {
Thread.sleep(3000);
connectionService.reconnect();
continue;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Notification notification = connectionService.waitForNotification();
if(notification == null){
continue;
}
processStartNotification(notification);
}
}
}).start();
}
在这里我开始连接:
public ConnectionService(String username){
this.username = username;
try{
socket = new Socket(BackgroundService.HOSTNAME, BackgroundService.PORT);
connected = true;
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeUTF(username);
output.flush();
}catch(UnknownHostException e){
connected = false;
}catch(IOException e){
connected = false;
}
}