gpt4 book ai didi

java - 使用套接字发送请求行+文件 - java

转载 作者:可可西里 更新时间:2023-11-01 02:49:07 24 4
gpt4 key购买 nike

我正在尝试通过套接字发送“请求行”和文件。

客户端(发送方)

Socket socket = new Socket(hostName, SOCKET_PORT);
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
FileInputStream fis = new FileInputStream(fileName);
os.writeBytes("PUT c:\dev\foo\helloworld.txt" + "\r\n")
byte[] buffer = new byte[1024];
int bytes;
while((bytes = fis.read(buffer)) != -1 ) {
try {
os.write(buffer, 0, bytes);
} catch (IOException e) {e.printStackTrace();}
}

服务器(接收方)

ServerSocket serverSocket = new ServerSocket(SOCKET_PORT);
Socket clientSoc = serverSocket.accept();
InputStream inputStream = clientSoc.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String requestLine = bufferedReader.readLine();
File currentFile = (File)new ObjectInputStream(inputStream).readObject(); //This doesn't work
byteSequence = new byte[new Long(currentFile.length()).intValue()];
for(int i =0; i<currentFile.length();i++){
byteSequence[i] = (byte)clientSoc.getInputStream().read();
}
try {
FileOutputStream newFile = new FileOutputStream(currentFile.getName());
newFile.write(byteSequence,0, byteSequence.length);
} catch (IOException e) {e.printStackTrace();}

我能够读取服务器上的请求行,但是当我尝试读取文件时它会抛出异常(下一行)。

File currentFile = (File)new ObjectInputStream(inputStream).readObject(); 

java.io.Stream.CorruptedException:

java.io.StreamCorruptedException: invalid stream header: 0A48656C

我究竟做错了什么?

最佳答案

您正在尝试访问一个甚至没有传递给套接字的对象。您只传递了一个字节的字符串到服务器,但您从未使用 ObjectOutputStream 将对象传递给服务器。

关于java - 使用套接字发送请求行+文件 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23966640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com