socket通信中,socket建立连接后能进行长时间的反复读写操作吗?

服务端和客户端以socket建立连接进行通信,我想以单线程实现多文件传输,循环发送多个文件,只是对输入输出流进行打开和关闭,为什么第一个文件传完后进行第二个文件传输时会抛异常:Socket is closed?求高手指点迷津,难道一定要关闭socket然后重新连接吗?

不需要,肯定是你代码写得有问题。不妨把代码贴出来看看

通过Socket连接一次传输多个文件

上代码看看,估计是你fclose()或者指针那里的句柄提前关闭了

while ((len = inStream.read(buffer)) != -1) {// 从输入流中读取数据写入到文件中
fileOutStream.write(buffer, 0, len);
length += len;
Message msg = mHandler.obtainMessage();
msg.getData().putString("order", "update_pbar");
msg.getData().putString("client_ip", clientId);
msg.getData().putString("filename", file.getName());
msg.getData().putInt("percent", (int) (100 * length / file.length()));
mHandler.sendMessage(msg);
mFileLog.delete(fileId);
mFileLog.insert(fileId, file.getAbsolutePath(), length + "");
}
// 文件接收完成
if (length == Long.parseLong(filelength)) {
fileOutStream.close();
inStream.close();
mFileLog.delete(fileId);
outStream.write("OK\n".getBytes("utf-8"));
outStream.close();
}
file = null;

上面的是服务端的代码,这两个都是做的安卓app;Message 是子线程发消息更新进度条。 mFileLog是我自己建的SQLlite数据库表的操作!
while ((len = fileOutStream.read(buffer)) != -1) {//将文件读到输出流
outStream.write(buffer, 0, len);
length += len;
Message msg = mHandler.obtainMessage();
msg.getData().putString("order", "update_pbar");
msg.getData().putString("filename", file.getName());
msg.getData().putInt("percent", (int) (100 * length / file.length()));
mHandler.sendMessage(msg);
}

                        fileOutStream.close();
                        outStream.close();
                        if (length == file.length()) {
                            // 文件上传完成删除记录,下次上传重新上传
                            String result = null;
                            BufferedReader br = new BufferedReader(new InputStreamReader(is));
                            while ((result = br.readLine()) != null) {
                                if (result.equals("OK")) {
                                    mLog.delete(fileId);
                                }
                            }
                            inStream.close();
                            br.close();
                        }

我想客户端发完一个文件后,等待服务端回复"OK"后再进行第二个文件的传输!可是while循环后不管关不关流,客户端和服务端总有一个要抛异常报socket is closed!

其实你关闭stream的时候,socket也关闭了。
This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.
大概设计者的意思是说,这是个全双工的通讯,Server端的职责是响应请求,所以一个流关闭,则socket也没办法工作了