如何解决线程和 FileOutputStream :虽然同步
我有一个简单的服务器类,它在套接字中接收数据片段,例如:WRITE#filename.txt#data
服务器必须将它接收到的数据写入同一个文件中。 当我测试它时,每个片段的“写作:”行都正确显示,“确定”也是如此:
Connection established
WRITE#file.txt#frag1\nthis is a fragment of text
writing : frag1\nthis is a fragment of text
ok
Connection established
WRITE#file.txt#fragment2\nthis is another fragment
writing : fragment2\nthis is another fragment
ok
Connection established
WRITE#file.txt#fragment3
writing : fragment3
ok
...但最后,我只看到服务器上文件中的第一个片段。但是第二个和第三个应该也写了,如上所示。
FileOutputStream 和 FileWriter 都会发生这种情况。
代码如下:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer extends Thread {
private Socket socket;
public static Object mutex = new Object();
public MyServer(final Socket socket) {
this.socket = socket;
}
public static void main(final String[] args) throws IOException {
final ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
MyServer h = new MyServer(serverSocket.accept());
h.start();
}
}
@Override
public void run() {
try {
System.out.println("Connection established");
// get data from client
final InputStream is = this.socket.getInputStream();
synchronized(mutex){
byte[] data = new byte[1024];
is.read(data);
String s = new String(data);
System.out.println(s);
// command: WRITE#filename#content
final String[] split_command = s.split("#");
final String commandtype = split_command[0];
final String filename = split_command[1];
final String data_frag = split_command[2]
switch (commandtype) {
case "WRITE":
// Write data_frag on the server
FileOutputStream fos = new FileOutputStream(PATH_SERVER + filename,true);
try {
System.out.println("writing : "+ data_frag);
fos.write(data_frag.getBytes());
System.out.println("ok");
}
catch (IOException e) {
System.out.println("exception!");
}
is.close();
this.socket.close();
fos.close();
break;
case "CMD_READ":
// Something else
break;
default:
System.out.println(commandtype + " : unknown");
}
} // end of synchronization
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
谢谢,
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。