从 Socket 读取时卡在写操作中
Stuck in write operation when reading from Socket
我正在通过 Socket 将文件及其名称发送到 ServerSocket。
它有效"partially"——服务器获取文件并将其保存到磁盘但是
它不会在 ClientSession class.
的 copy() 方法中退出循环
public class Client{
DataOutputStream dos =null;
DataInputStream dis=null;
File f =new File("c:/users/supernatural.mp4");
public static void main(String[]ar) throws Exception{
try {
System.out.println("File upload started");
Socket socc = new Socket("localhost",8117);
dos = new DataOutputStream(socc.getOutputStream());
//send file name
dos.writeUTF(f.getName());
//send the file
write(f,dos);
//Files.copy(f.toPath(),dos);
//this prints
System.out.println("Data has been sent...waiting for server to respond ");
dis = new DataInputStream(socc.getInputStream());
//this never reads; stuck here
String RESPONSE = dis.readUTF();
//this never prints prints
System.out.println("Server sent: "+RESPONSE);
} catch(Exception ex) {
ex.printStackTrace();
} finally {
//close the exceptions
clean();
}
}
private static void write(File f,DataOutputStream d) throws Exception{
int count;
DataInputStream din = new DataInputStream(new BufferedInputStream(new FileInputStream(f)));
byte array[] = new byte[1024*4];
while((count =din.read(array)) >0){
d.write(array,0,count);
}
d.flush();
//this prints
System.out.println(" done sending...");
din.close();
}
}
//Server
public class MySocket implements Runnable{
int worker_thread=2;
volatile boolean shouldRun =false;
ServerSocket server;
String port = "8117";
//ExecutorService services;
static ExecutorService services;
public MySocket() {
this.server = new ServerSocket(Integer.valueOf(port));
services = Executors.newFixedThreadPool(this.worker_thread);
}
//A METHOD TO RUN SERVER THREAD
@Override
public void run(){
while(this.shouldRun){
Socket client =null;
try{
client = server.accept();
}catch(Exception ex){
ex.printStackTrace();
}
//hand it over to be processed
this.services.execute(new ClientSessions(client));
}
}
public static void main(String[]ar) throws Exception{
Thread t = new Thread(new MySocket());
t.start();
}
}
//the ClientSession
public class ClientSessions implements Runnable{
Socket s;
public ClientSessions(Socket s){
this.s = s;
}
DataInputStream dis=null;
DataOutputStream dos=null;
boolean success =true;
@Override
public void run(){
//get the data
try{
//get inside channels
dis = new DataInputStream(this.s.getInputStream());
//get outside channels
dos = new DataOutputStream(this.s.getOutputStream());
//read the name
//this works
String name=dis.readUTF();
String PATH_TO_SAVE ="c://folder//"+name;
//now copy file to disk
File f = new File(PATH_TO_SAVE);
copy(f,dis);
//Files.copy(dis,f.toPath());
//this doesnt print, stuck in the copy(f,dis) method
System.out.println("I am done");
success =true;
}catch(Exception ex){
ex.printStackTrace();
}finally{
//clean resources...
clean();
}
}
//copy from the stream to the disk
private void copy(File f,DataInputStream d)throws Exception{
f.getParentFile().mkdirs();
f.createNewFile();
int count =-1;
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
byte array[] = new byte[1024*8];
count =d.read(array);
while(count >0){
out.write(array,0,count);
count =d.read(array);
System.out.println("byte out: "+count);
}
//this never prints
System.out.println("last read: "+count);
out.flush();
out.close();
if(success)dos.writeUTF("Succesful");
else dos.writeUTF("error");
}
}
//for the clean method i simply have
void clean(){
if(dis!=null)dis.close();
if(dos!=null)dos.close();
}
我评论了这个 //Files.copy(dis,f.toPath());从服务器
因为写文件到磁盘后不会跳到下一行,有时甚至卡在那里。
有人能给我指明正确的道路吗,我相信我在这里做错了
不知道这是否有帮助,但客户端在 eclipse 中运行,服务器在 netbeans 中运行
想想你的协议:
- 客户端发送文件名,然后发送二进制文件,然后等待服务器响应。
- 服务器读取文件名,然后是二进制文件,直到流关闭,然后发送成功消息。
但是由于客户端正在等待响应,因此流永远不会关闭,因此您的协议出现了死锁。
这通常可以通过先发送文件大小并让服务器准确读取那么多字节来解决。
或者,您可以使用 TCP 的单向关闭功能向服务器发送一个信号,表明套接字的输出流已关闭。这可以用 socc.shutdownOutput();
来完成
并且请使用try-with-resources以避免资源泄漏(您也必须关闭Socket)。
固定客户端:
try {
System.out.println("File upload started");
try (Socket socc = new Socket("localhost", 8117);
DataOutputStream dos = new DataOutputStream(socc.getOutputStream());
DataInputStream dis = new DataInputStream(socc.getInputStream())) {
// send file name
dos.writeUTF(f.getName());
// send the file
Files.copy(f.toPath(), dos);
dos.flush();
System.out.println("Data has been sent...waiting for server to respond ");
// signal to server that sending is finished
socc.shutdownOutput();
String RESPONSE = dis.readUTF();
// this never prints prints
System.out.println("Server sent: " + RESPONSE);
}
} catch (Exception ex) {
ex.printStackTrace();
}
服务器:
public class MySocket implements Runnable {
int worker_thread = 2;
volatile boolean shouldRun = true;
ServerSocket server;
int port = 8117;
ExecutorService services;
public MySocket() throws IOException {
this.server = new ServerSocket(port);
services = Executors.newFixedThreadPool(this.worker_thread);
}
// A METHOD TO RUN SERVER THREAD
@Override
public void run() {
while (this.shouldRun) {
Socket client = null;
try {
client = server.accept();
} catch (Exception ex) {
ex.printStackTrace();
}
// hand it over to be processed
this.services.execute(new ClientSessions(client));
}
}
public static void main(String[] ar) throws Exception {
new MySocket().run();
}
}
class ClientSessions implements Runnable {
Socket s;
public ClientSessions(Socket s) {
this.s = s;
}
@Override
public void run() {
// get the data
try (DataInputStream dis = new DataInputStream(this.s.getInputStream());
DataOutputStream dos = new DataOutputStream(this.s.getOutputStream())) {
// read the name
// this works
String name = dis.readUTF();
String PATH_TO_SAVE = name;
// now copy file to disk
File f = new File("c://folder", PATH_TO_SAVE);
Files.copy(dis, f.toPath());
dos.writeUTF("Succesful");
System.out.println("I am done");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
您的代码的问题是,您从永远不会关闭的套接字的输入流中读取。
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
byte array[] = new byte[1024*8];
count =d.read(array);
while(count >0){
out.write(array,0,count);
count =d.read(array);
System.out.println("byte out: "+count);
}
//this never prints
System.out.println("last read: "+count);
d.read(array)
正在积极尝试从套接字中读取,阻塞直到它收到一些东西。由于 InputStream 处于主动阻塞状态,因此它永远不会 return 小于或等于 0 的值。这是因为流等待来自 Socket 另一端的下一个包。
发送文件后关闭套接字应该对您有所帮助。在这种情况下,到达流的末尾并且 InputStream returns。
注意:您正在读取的 InputStream 将(如果套接字已关闭)return a -1,正如您在 JavaDoc.
在你的情况下,这可能不可行!
您想用 "okay" 或 "error" 回答客户。如果关闭套接字,则无法通过同一个套接字应答。这个问题的解决方案可能很复杂。
这个情况有点棘手。大多数框架都有一个线程,它从 SocketInputStream 读取并将 return 值传递给某种处理程序(在阻塞 IO 中)。您的 while 循环基本上是 Thread 中的主要读取循环。如果连接丢失,此循环只会退出,因此 System.out.println("last read: "+count);
可以更改为 System.out.println("disconnected");
为简单起见:您可以估计文件的 大小 并且(仅用于测试目的)编写如下内容:
DataOutputStream out = new DataOutputStream(new
BufferedOutputStream(new FileOutputStream(f)));
byte array[] = new byte[/* Big enough */ 1024 * 1024 * 8];
d.read(array); // Read the file content
out.write(array); // Write to the file
//this never prints
System.out.println("last read: "+count);
我在这里省略了所有错误检查!这意味着您只能从服务器读取 一个 包,它必须是文件。
我正在通过 Socket 将文件及其名称发送到 ServerSocket。 它有效"partially"——服务器获取文件并将其保存到磁盘但是 它不会在 ClientSession class.
的 copy() 方法中退出循环public class Client{
DataOutputStream dos =null;
DataInputStream dis=null;
File f =new File("c:/users/supernatural.mp4");
public static void main(String[]ar) throws Exception{
try {
System.out.println("File upload started");
Socket socc = new Socket("localhost",8117);
dos = new DataOutputStream(socc.getOutputStream());
//send file name
dos.writeUTF(f.getName());
//send the file
write(f,dos);
//Files.copy(f.toPath(),dos);
//this prints
System.out.println("Data has been sent...waiting for server to respond ");
dis = new DataInputStream(socc.getInputStream());
//this never reads; stuck here
String RESPONSE = dis.readUTF();
//this never prints prints
System.out.println("Server sent: "+RESPONSE);
} catch(Exception ex) {
ex.printStackTrace();
} finally {
//close the exceptions
clean();
}
}
private static void write(File f,DataOutputStream d) throws Exception{
int count;
DataInputStream din = new DataInputStream(new BufferedInputStream(new FileInputStream(f)));
byte array[] = new byte[1024*4];
while((count =din.read(array)) >0){
d.write(array,0,count);
}
d.flush();
//this prints
System.out.println(" done sending...");
din.close();
}
}
//Server
public class MySocket implements Runnable{
int worker_thread=2;
volatile boolean shouldRun =false;
ServerSocket server;
String port = "8117";
//ExecutorService services;
static ExecutorService services;
public MySocket() {
this.server = new ServerSocket(Integer.valueOf(port));
services = Executors.newFixedThreadPool(this.worker_thread);
}
//A METHOD TO RUN SERVER THREAD
@Override
public void run(){
while(this.shouldRun){
Socket client =null;
try{
client = server.accept();
}catch(Exception ex){
ex.printStackTrace();
}
//hand it over to be processed
this.services.execute(new ClientSessions(client));
}
}
public static void main(String[]ar) throws Exception{
Thread t = new Thread(new MySocket());
t.start();
}
}
//the ClientSession
public class ClientSessions implements Runnable{
Socket s;
public ClientSessions(Socket s){
this.s = s;
}
DataInputStream dis=null;
DataOutputStream dos=null;
boolean success =true;
@Override
public void run(){
//get the data
try{
//get inside channels
dis = new DataInputStream(this.s.getInputStream());
//get outside channels
dos = new DataOutputStream(this.s.getOutputStream());
//read the name
//this works
String name=dis.readUTF();
String PATH_TO_SAVE ="c://folder//"+name;
//now copy file to disk
File f = new File(PATH_TO_SAVE);
copy(f,dis);
//Files.copy(dis,f.toPath());
//this doesnt print, stuck in the copy(f,dis) method
System.out.println("I am done");
success =true;
}catch(Exception ex){
ex.printStackTrace();
}finally{
//clean resources...
clean();
}
}
//copy from the stream to the disk
private void copy(File f,DataInputStream d)throws Exception{
f.getParentFile().mkdirs();
f.createNewFile();
int count =-1;
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
byte array[] = new byte[1024*8];
count =d.read(array);
while(count >0){
out.write(array,0,count);
count =d.read(array);
System.out.println("byte out: "+count);
}
//this never prints
System.out.println("last read: "+count);
out.flush();
out.close();
if(success)dos.writeUTF("Succesful");
else dos.writeUTF("error");
}
}
//for the clean method i simply have
void clean(){
if(dis!=null)dis.close();
if(dos!=null)dos.close();
}
我评论了这个 //Files.copy(dis,f.toPath());从服务器 因为写文件到磁盘后不会跳到下一行,有时甚至卡在那里。
有人能给我指明正确的道路吗,我相信我在这里做错了 不知道这是否有帮助,但客户端在 eclipse 中运行,服务器在 netbeans 中运行
想想你的协议:
- 客户端发送文件名,然后发送二进制文件,然后等待服务器响应。
- 服务器读取文件名,然后是二进制文件,直到流关闭,然后发送成功消息。
但是由于客户端正在等待响应,因此流永远不会关闭,因此您的协议出现了死锁。
这通常可以通过先发送文件大小并让服务器准确读取那么多字节来解决。
或者,您可以使用 TCP 的单向关闭功能向服务器发送一个信号,表明套接字的输出流已关闭。这可以用 socc.shutdownOutput();
并且请使用try-with-resources以避免资源泄漏(您也必须关闭Socket)。
固定客户端:
try {
System.out.println("File upload started");
try (Socket socc = new Socket("localhost", 8117);
DataOutputStream dos = new DataOutputStream(socc.getOutputStream());
DataInputStream dis = new DataInputStream(socc.getInputStream())) {
// send file name
dos.writeUTF(f.getName());
// send the file
Files.copy(f.toPath(), dos);
dos.flush();
System.out.println("Data has been sent...waiting for server to respond ");
// signal to server that sending is finished
socc.shutdownOutput();
String RESPONSE = dis.readUTF();
// this never prints prints
System.out.println("Server sent: " + RESPONSE);
}
} catch (Exception ex) {
ex.printStackTrace();
}
服务器:
public class MySocket implements Runnable {
int worker_thread = 2;
volatile boolean shouldRun = true;
ServerSocket server;
int port = 8117;
ExecutorService services;
public MySocket() throws IOException {
this.server = new ServerSocket(port);
services = Executors.newFixedThreadPool(this.worker_thread);
}
// A METHOD TO RUN SERVER THREAD
@Override
public void run() {
while (this.shouldRun) {
Socket client = null;
try {
client = server.accept();
} catch (Exception ex) {
ex.printStackTrace();
}
// hand it over to be processed
this.services.execute(new ClientSessions(client));
}
}
public static void main(String[] ar) throws Exception {
new MySocket().run();
}
}
class ClientSessions implements Runnable {
Socket s;
public ClientSessions(Socket s) {
this.s = s;
}
@Override
public void run() {
// get the data
try (DataInputStream dis = new DataInputStream(this.s.getInputStream());
DataOutputStream dos = new DataOutputStream(this.s.getOutputStream())) {
// read the name
// this works
String name = dis.readUTF();
String PATH_TO_SAVE = name;
// now copy file to disk
File f = new File("c://folder", PATH_TO_SAVE);
Files.copy(dis, f.toPath());
dos.writeUTF("Succesful");
System.out.println("I am done");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
您的代码的问题是,您从永远不会关闭的套接字的输入流中读取。
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
byte array[] = new byte[1024*8];
count =d.read(array);
while(count >0){
out.write(array,0,count);
count =d.read(array);
System.out.println("byte out: "+count);
}
//this never prints
System.out.println("last read: "+count);
d.read(array)
正在积极尝试从套接字中读取,阻塞直到它收到一些东西。由于 InputStream 处于主动阻塞状态,因此它永远不会 return 小于或等于 0 的值。这是因为流等待来自 Socket 另一端的下一个包。
发送文件后关闭套接字应该对您有所帮助。在这种情况下,到达流的末尾并且 InputStream returns。
注意:您正在读取的 InputStream 将(如果套接字已关闭)return a -1,正如您在 JavaDoc.
在你的情况下,这可能不可行!
您想用 "okay" 或 "error" 回答客户。如果关闭套接字,则无法通过同一个套接字应答。这个问题的解决方案可能很复杂。
这个情况有点棘手。大多数框架都有一个线程,它从 SocketInputStream 读取并将 return 值传递给某种处理程序(在阻塞 IO 中)。您的 while 循环基本上是 Thread 中的主要读取循环。如果连接丢失,此循环只会退出,因此 System.out.println("last read: "+count);
可以更改为 System.out.println("disconnected");
为简单起见:您可以估计文件的 大小 并且(仅用于测试目的)编写如下内容:
DataOutputStream out = new DataOutputStream(new
BufferedOutputStream(new FileOutputStream(f)));
byte array[] = new byte[/* Big enough */ 1024 * 1024 * 8];
d.read(array); // Read the file content
out.write(array); // Write to the file
//this never prints
System.out.println("last read: "+count);
我在这里省略了所有错误检查!这意味着您只能从服务器读取 一个 包,它必须是文件。