gpt4 book ai didi

java - 文件管理客户端-服务器编程

转载 作者:行者123 更新时间:2023-12-01 14:36:21 25 4
gpt4 key购买 nike

我陷入了这种客户端-服务器编程的困境,我希望服务器维护一个文件,该文件存储客户端发送的数据。代码如下:

客户端:

public class ClientSide {
public static void main(String[] argv) throws Exception {

String sentence;
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');
clientSocket.close();
}
}

服务器端:

public class ServerSide {
public static void main(String[] args) throws IOException {
File file=new File("s1.txt");
ServerSocket servsock = new ServerSocket(6789);

Socket sock = servsock.accept();
byte[] mybytearray = new byte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream(file,true);
BufferedOutputStream bos = new BufferedOutputStream(fos);

int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);

bos.close();
sock.close();

BufferedReader write=new BufferedReader(new FileReader(file));
String line;
while((line=write.readLine())!=null) {
System.out.println(line);
}

}
}

现在,当用户向服务器发送数据时,例如“Vinayak”是发送到服务器的数据,只有第一个字符,即“V”写入文件。我一定是在代码中遗漏了一些东西,但我找不到它。另外,我问过类似的问题here但是,无法得到想要的结果

最佳答案

您应该检查读取操作是否实际上在服务器端读取了您想要的字节数。请参阅javadocs for InputStream :

The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

...

The read(b, off, len) method for class InputStream simply calls the method read() repeatedly. If the first such call results in an IOException, that exception is returned from the call to the read(b, off, len) method. If any subsequent call to read() results in a IOException, the exception is caught and treated as if it were end of file; the bytes read up to that point are stored into b and the number of bytes read before the exception occurred is returned

将服务器读取代码更改为循环:

    int bytesRead = -1;
while ((bytesRead = is.read(mybytearray, 0, mybytearray.length)) != -1) {
System.out.println(bytesRead);
bos.write(mybytearray, 0, bytesRead);
}

服务器端输出:

1
85
9
9
...
5
10
8
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin fermentum facilisis nulla id aliquet. Suspendisse venenatis condimentum erat adipiscing interdum. Etiam aliquet iaculis mauris lacinia lacinia. Morbi nec nisi est. Duis vel nunc a risus scelerisque feugiat. Morbi eget odio ac arcu vehicula facilisis vel ut nibh. Morbi sodales tristique ante eu aliquam. Ut a leo nisi. Morbi eu purus sed lectus mattis tincidunt.

关于java - 文件管理客户端-服务器编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16457746/

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