[求助]关于java的心跳包程序出现java.net.SocketException: Software caused connection abort: socket write error

来源:互联网 发布:linux命令行删除文件 编辑:程序博客网 时间:2024/05/17 09:31

客户端代码:

package com.eason.socket;


import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;


/**
 * @author Eric.Hao
 *
 */
public class Client {


/**
* @param args
*/
public static void main(String[] args) {
int port = 9999;
Socket client = null;
String ip = "127.0.0.1";
int cout = 0 ;

// 构造客户端socket对象
try {


client = new Socket(ip, port);
OutputStream out = client.getOutputStream();
System.out.println("客户端启动");
while(true)
{
cout++;

Thread.sleep(5000);
out.write(String.valueOf(System.currentTimeMillis()).getBytes());

if(cout>50)
{
client.close();
break;
}
}
System.out.println("客户端退出");
} catch (Exception e) {
e.printStackTrace();


}
finally
{

System.out.println("退出");
}
}


}


主机代码:

/**
 * 
 */
package com.eason.socket;


import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;


/**
 * @author Eric.Hao
 *
 */
public class Server {


/**
* @param args
*/
public static void main(String[] args) {

try {
ServerSocket server = new ServerSocket(9999);
while(true)
{
//接受客户机的连接请求
Socket client = server.accept();
new TestServer(client).start();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

static class TestServer extends Thread
{


Socket client  = null ;

public TestServer(){

}

public TestServer(Socket client)
{
this.client = client ;
}

@Override
public void run() {

try
{
InputStream is = this.client.getInputStream();
while(true)
{
if (this.client.isClosed()
|| this.client.isConnected() == false)
break;

try {
// 方法sendUrgentData,往输出流发送一个字节的数据
// 只要对方
// Socket的SO_OOBINLINE属性没有打开,就会自动舍弃这个字节,而SO_OOBINLINE属性默认情况下就是关闭的
// 如果客户端 开启了 ,就需要处理
this.client.sendUrgentData(0xFF);
System.out.println(Thread.currentThread().getName()+"=>"+"心跳测试正常!");
} catch (Exception ex) {
System.out.println(Thread.currentThread().getName()+"=>"+"心跳测试异常!");
break;
}
byte []data =  new byte[13];
is.read(data);
System.out.println(Thread.currentThread().getName()+"=>"+new String(data));
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
finally
{
System.out.println(Thread.currentThread().getName()+"=>"+"客户端关闭");
}
}

}


}


运行之后刚开始是正常运行的,到后面就会弹出

java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at com.eason.socket.Client.main(Client.java:36)

0 0
原创粉丝点击