好的,我正在开发一个程序来保存向量中多个文件的名称和路径,并将它们从服务器发送到客户端。所以我只是尝试发送一个带有单个条目的单个矢量文件,但无济于事。Client 代码中的向量初始化确实有点奇怪,使用 ObjectInput 和 ObjectOutput 接口发送向量是不是不对?还是我只是做错了?服务器代码:
import java.io.*;
import java.net.*;
import java.util.*;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
Vector<String> name = new Vector<String>(3, 1);
File f0=new File("C:/Downloads","hjd");
name.addElement(f0.getName());
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
if(clientSentence!="hjd")
outToClient.writeBytes("Please enter correct directory/filename");
else{
OutputStream socketStream = connectionSocket.getOutputStream();//output stream where the object is to be written
ObjectOutput objectOutput = new ObjectOutputStream(socketStream);
objectOutput.writeObject(name);//no error during compilation of this line however
}
}
}
给我一个不兼容类型的客户端代码在向量声明行中发现错误:
import java.io.*;
import java.net.*;
import java.util.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
String sentence;
System.out.println("Enter name of file as hjd");//I will later expand this to add more options
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
InputStream socketStream = clientSocket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(socketStream);
Vector<String> name = objectInput.readObject();//This is the line I am recieving an error on,saying "incompatible types found"
System.out.println("The name of file is:"+name.get(0));
clientSocket.close();
}
}
总结一下,我可以使用这些接口发送矢量吗?如果不是,那么如何通过 TCP 发送向量?如果是,那么错误行的正确声明是什么,因为这个甚至没有提到的向量的大小或增量?
编辑——现在感谢 ALex,错误消失了。我已经编辑了该声明:
if(objectInput.readObject() instanceof String){
String a=(String)objectInput.readObject();
System.out.println("The name of file is:"+a);
}else if(objectInput.readObject() instanceof Vector){
Vector<String> name=(Vector<String>)objectInput.readObject();
System.out.println("The name of file is:"+name.get(0)); }
但是在运行程序时会生成一个异常,说我的 ObjectInputStream 已损坏。我错过了什么?