我基本上想从服务器发送一个数组列表到我的客户端,它必须被序列化,所以我使用 ObjectI/OStream。但这是第一次创建客户端/服务器程序,所以我真的不知道该怎么做。我什至无法在客户端程序中构造 ObjectInputStream 构造函数。我得到错误:
线程“主”java.net.SocketException 中的异常:对等方重置连接:java.net.SocketOutputStream.socketWrite0(本机方法)处 java.net.SocketOutputStream.socketWrite(未知源)处的套接字写入错误 java.net.SocketOutputStream .write(Unknown Source) at java.io.ObjectOutputStream$BlockDataOutputStream.drain(Unknown Source) at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(Unknown Source) at java.io.ObjectOutputStream.(Unknown Source) at SalesServer.main(销售服务器.java:35)
代码:
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class SalesClient {
public static void main(String[] args) throws IOException{
Socket ssocket = null;
ObjectOutputStream out = null;
ObjectInputStream inp = null;
Scanner in = null;
try {
ssocket = new Socket("FahadAhmed-PC", 6667);
in = new Scanner(System.in);
inp = new ObjectInputStream();
}catch(UnknownHostException e) {
System.err.println("Don't know about host: FahadAhmed-PC");
System.exit(1);
}catch(IOException e){
System.err.println(e);
System.exit(1);
}
}
}
服务器代码。首先它扫描一个文本文件,然后将一个销售对象添加到 arraylist:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesServer {
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(6667);
} catch (IOException e){
System.out.println("Could not listen on port: 5555.");
System.exit(1);
}
Socket clientSocket = null;
try{
clientSocket = serverSocket.accept();
}catch (IOException e){
System.out.println("Accept failed.");
System.exit(1);
}
ArrayList<Sales> salesList = getSalesList();
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
}
private static ArrayList<Sales> getSalesList() throws FileNotFoundException {
ArrayList<Sales> list = new ArrayList<Sales>(10);
Scanner in = new Scanner(new BufferedReader(new FileReader("sales.txt")));
while(in.hasNext()){
String state;
int q1, q2, q3, q4;
state = in.nextLine();
q1 = in.nextInt();
q2 = in.nextInt();
q3 = in.nextInt();
q4 = in.nextInt();
in.nextLine();
Sales sale = new Sales(state, q1, q2, q3, q4);
System.out.println(sale.toString());
list.add(sale);
}
return null;
}
}