日期:2014-05-18  浏览次数:20609 次

socket客户端往服务端发送数据异常
客户端code


public class Client implements Runnable{

private static Socket s;

private Socket getInstance(){
if(s==null){
try {
return s=new Socket("127.0.0.1",8000);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();

}
return s;
}

public void sendMsg() {
while(true){
try {
run();
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

@Override
public void run() {
System.out.println("come into run");
try {
Socket c = getInstance();
OutputStream ops =c.getOutputStream();
ops.write(new byte[]{0000});
ops.flush();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}

public static void main(String[] args) {
Client c = new Client();
c.sendMsg();
}
}



服务端code

public class Server {

private ServerSocket serverSocket;

public Server(){
try {
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress(8000));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("服务启动");
}

public void service() {
while (true) {
Socket s = null;
try {
s = serverSocket.accept();
System.out.println("come a new request~ "+s.getInetAddress()+":"+s.getPort());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(s!=null)
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
Server server = new Server();
server.service();
}
}



我的想法是每隔3秒往服务端发送一个数据包,现在的情况是会抛异常:
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.ls.test.Clie