java socket 重连_重新连接后,Java Socket连接“崩溃”

我想在我的服务器和客户端之间创建套接字连接 . 在连接超时后,我的客户端应该重新连接 . 为此,我每隔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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值