2023年12月8日发(作者:)
异常:Softwarecausedconnectionabort:socketwriteerror
最近在实验《Tomcat与Java Web开发技术详解》书中例子程序时,发现一个异常:Software caused connection abort: socket write error
用Java 套接字创建HTTP 客户与服务器程序
服务器程序
package sever;
import tream;
import Stream;
import .*;
public class HTTPServer {
/**
* @param args
*/
public static void main(String[] args) {
int port;
ServerSocket serverSocket;
try{
port = nt(args[0]);
}catch(Exception e){
n("port = 8080 (默认)");
port = 8080;
}
try{
serverSocket = new ServerSocket(port);
n("服务器正在监听端口: "+alPort());
while(true){
try{
//等待客户的TCP连接请求
final Socket socket = ();
n("建立一个客户端的新的TCP连接,该客户的地址为:"+tAddress()+":"+t());
service(socket);
}catch(Exception e){
tackTrace();
}
}
}catch(Exception e){
tackTrace();
}
}
public static void service(Socket socket)throws Exception {
// TODO Auto-generated method stub
/*读取HTTP请求信息*/
InputStream socketIn = utStream();
(500);
int size = ble();
byte[] buffer = new byte[size];
(buffer);
String request = new String(buffer);
n(request);
/*解析HTTP请求*/
//获得HTTP请求的第一行
String firstLineOfRequest=ing(0,f("rn"));
//解析HTTP请求的第一行 String[] parts=(" ");
String uri = parts[1];
/*决定HTTP响应正文的类型,*/
String contentType ;
if(f("html")!=-1||f("htm")!=-1)
{
contentType="txt/html";
}
else if(f("jpg")!=-1||f("jpeg")!=-1)
{
contentType = "image/jpeg";
}
else if(f("gif")!=-1)
{
contentType = "image/gif";
}
else
{
contentType = "application/octet-stream";
}
/*创建HTTP响应结果*/
//HTTP响应第一行
String responseFirstLine = "HTTP/1.1 200 OK rn";
//HTTP响应头
String responseHeader = "Content-Type:"+contentType+"rnrn";
//获得响应正文数的输入流
InputStream in = ourceAsStream("root/"+uri);
/*发送HTTP响应结果*/
OutputStream socketOut = putStream();
//发送HTTP响应的第一行
(es());
//发送HTTP响应的头
(es());
//发送HTTP响应的正文
int len=0;
buffer = new byte[128];
while((len=(buffer))!=-1)
{
(buffer,0,len);
}
(1000);
();
}
}
客户端程序
package client;
import tream;
import Stream;
import ;
public class HTTPClient {
/**
* @param args
*/
public static void main(String[] args) {
//确定HTTP请求的uri
String uri="";
if(!=0) {
uri=args[0];
doGet("localhost",8080,uri);
}
}
public static void doGet(String host, int port, String uri) {
Socket socket = null;
try
{
socket=new Socket(host,port);
}
catch(Exception e)
{
tackTrace();
}
try
{
//创建HTTP请求
StringBuffer sb = new StringBuffer("GET "+uri+" HTTP/1.1rn");
//HTTP请求头
("Accept: */*rn");
("Accept-Language: zh-cnrn");
("Accept-Encoding: gzip, deflatern");
("User-Agent: HTTPClientrn");
("Host: localhost:8080rn");
("Connection: Keep-Alivernrn");
//发送HTTP请求
OutputStream socketOut = putStream();
(ng().getBytes());
(2000);
//接收响应结果
InputStream socketIn = utStream();
int size = ble();
byte[] buffer = new byte[size];
(buffer);
n(new String(buffer));
}
catch(Exception e)
{
tackTrace();
}
finally
{
try
{
();
}
catch(Exception e)
{
tackTrace();
}
}
}
}
执行过程:1.在eclipse中对服务端程序debug启动
2.在eclipse中对客户端程序debug启动,配置启动参数“”
3.在服务端红色部分,函数service中设置断点,单步调试,出现异常Software caused connection abort: socket write error分析:单步调试耗时比较长,服务端接收的socket已经被关闭。


发布评论