初学者
用ObjectOutputStream从服务端传送给客户端
传输对象少还没问题
对象数据稍微多一点就传不完整,并且客户端抛出
connection reset
在网上搜了好久,知道产生的原因是客户端没有接受完全,服务端退出导致的
但是不知道怎么解决
初学者很多东西也看不懂
还请赐教
客户端代码:
package com;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class AllDetails {
public AllDetails() {
}
@SuppressWarnings("unchecked")
public ArrayList<Detail> getAllDetails(int z_m) {
Conn conn = new Conn();// 实例化远程连接类,准备远程连接
ArrayList<Detail> allDetails = new ArrayList<Detail>();
try {
Socket client = new Socket(conn.getAddress(), conn.getPort());// 实例化客户端
// 传输请求信息
DataOutputStream outData = new DataOutputStream(client.getOutputStream());
outData.writeUTF("AllDetails|" + z_m);
// 接收结果
ObjectInputStream getBack = new ObjectInputStream(client.getInputStream());
allDetails = (ArrayList<Detail>) getBack.readObject();
client.close();// 关闭远程连接
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return allDetails;
}
}
服务端代码:
package main;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import com.AllDetails;
import com.Detail;
public class ReServer {
public ReServer() {
while (true) {
try {
ServerSocket serverSocket = new ServerSocket(3402);
Socket client = serverSocket.accept();
DataInputStream request = new DataInputStream(client.getInputStream());
String[] requestArray = request.readUTF().split("\\|");// 将客户端传来的请求,生成String数组
if (requestArray[0].equals("AllDetails")) {
ArrayList<Detail> result = new ArrayList<Detail>();
result = new AllDetails().getDetails(Integer.parseInt(requestArray[1]));// 调用查询程序,并获取结果
ObjectOutputStream resultOut = new ObjectOutputStream(client.getOutputStream());
resultOut.writeObject(result);
}
client.close();
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}