关于关机后网络异常的捕获
hibor 2000-07-22 11:39:00 十分奇怪,当客户端非正常关机后(暴力关机)服务器居然没有抛异常请各位帮忙看看
服务器代码:
import java.io.IOException;
import java.net.ServerSocket;
import java.io.InputStream;
import java.net.Socket;
public class TSrv
{
TSrv(int port)
{
try
{
_ServerSocket = new ServerSocket(port);
}
catch(IOException ex)
{
System.out.println(ex);
System.exit(1);
}
}
ServerSocket _ServerSocket;
public void getSrv()
{
while(true)
{
try
{
Socket socket = _ServerSocket.accept();
(new TSrvService(socket)).start();
}
catch(IOException ex)
{
System.out.println(ex);
continue;
}
}
}
public static void main(String[] s)
{
TSrv tsrv = new TSrv(10001);
tsrv.getSrv();
}
}
class TSrvService extends Thread
{
Socket _Socket;
TSrvService(Socket sock)
{
_Socket = sock;
}
public void run()
{
try
{
InputStream in = _Socket.getInputStream();
while(true)
{
try
{
int b = in.read();
System.out.println("Read byte:"+(byte)b);
}
catch(IOException ex)
{
System.out.println(ex);
return;
}
}
}
catch(IOException ex)
{
System.out.println(ex);
System.exit(1);
}
}
}
客户端代码:
import java.net.Socket;
import java.io.OutputStream;
import java.io.IOException;
public class TCli
{
Socket _Socket;
public TCli(String s,int p)
{
try
{
_Socket = new Socket(s,p);
}
catch(IOException ex)
{
System.out.println(ex);
System.exit(1);
}
}
public void getService()
{
try
{
OutputStream out = _Socket.getOutputStream();
while(true)
{
out.write(49);
synchronized(this)
{
try
{
wait(1000);
}
catch(Exception ex)
{;
}
}
}
}
catch(IOException ex)
{
System.out.println(ex);
System.exit(1);
}
}
public static void main(String[] s)
{
String server="98.0.0.200";
if(s.length>0)
{
server=s[0];
}
TCli tcli = new TCli(server,10001);
tcli.getService();
}
}