我坚持使用这种客户端-服务器编程,我希望服务器在其中维护一个文件,该文件存储客户端发送的数据。代码如下:
客户端:
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 ”被写入文件。我一定在代码中遗漏了一些东西,我找不到它。另外,我在这里问了类似的问题,但是无法得到想要的结果