问题描述:有一个非常简单的Socket服务器Server.java,客户端编写一个Socket访问该服务器
客户端从本地读取一个流,然后把这个流发送给服务器
服务器接受到这个流之后,进行流的解析,在控制台打印文件内容,然后向客户端返回一个字符串,
客户端等待该服务器响应,然后打印该字符串
结果是控制台只打印文件流,而不给客户端的socket返回响应字符串
代码如下:
Server.java
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket ss = null;
try {
while (true) {
ss = new ServerSocket(8888);
// 服务器接收到客户端的数据后,创建与此客户端对话的Socket
Socket socket = ss.accept();
// 用于向客户端发送数据的输出流
DataOutputStream dos = new DataOutputStream(socket
.getOutputStream());
// 用于接收客户端发来的数据的输入流
DataInputStream dis = new DataInputStream(socket
.getInputStream());
System.out.println("发送的文件为");
InputStreamReader isr=new InputStreamReader(dis);
BufferedReader reader=new BufferedReader(isr);
String line=null;
try {
while((line=reader.readLine())!=null){
System.out.println(line);
}
} catch (IOException e) {
}
// 服务器向客户端发送连接成功确认信息
reader.close();
isr.close();
dos.writeUTF("接受连接请求,连接成功!");
dos.flush();
socket.close();
ss.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端代码:
public class Client {
public static void main(String[] args) throws Exception {
Socket socket = null;
try {
socket = new Socket("localhost",8888);
//获取输出流,用于客户端向服务器端发送数据
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
//获取输入流,用于接收服务器端发送来的数据
DataInputStream dis = new DataInputStream(socket.getInputStream());
//客户端向服务器端发送数据
// dos.writeUTF("我是客户端,请求连接!");
byte []bf=new byte[1024];
InputStream is=new FileInputStream("D:/avatar.xml");
int w=0;
while((w=is.read(bf))!=-1){
dos.write(bf,0,w);
}
//打印出从服务器端接收到的数据
System.out.println(dis.readUTF());
//不需要继续使用此连接时,记得关闭
// socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果为:
发送的文件为
<?xml version="1.0" encoding="utf-8"?>
<userinfo>
<st>1</st>
<sex>1</sex>
<em>1</em>
<avatar_male>0101000001000100000000000001000000</avatar_male>
<avatar_female>0001000001000100000000000001000000</avatar_female>
<bg>10</bg>
</userinfo>
当我停止服务器时,控制台结果如下
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.readUnsignedShort(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at net.tcp.demo.Client.main(Client.java:32)
请问各位大侠,这个事怎么回事啊?