发送文件后通过套接字发送文本 [英] Sending a text over socket after sending a file

查看:86
本文介绍了发送文件后通过套接字发送文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个客户端,它将向服务器发送文件...服务器将文件分块获取并处理数据,然后将其发送回服务器.后来,在文件完全传输之后,我希望服务器告诉客户端数据是否已处理,有无错误.

I have a client which will send a file to the server...the server gets the file in chunks and processes the data and send it back to the server. Later, after the file has bee transmitted fully, i want the server to tell the client whether the data was processed with or without any errors.

客户端:使用此代码发送和接收文件数据

    toServer = socket.getOutputStream();
    fromServer = socket.getInputStream();
    fileReader = new BufferedInputStream(fis);
    fileWriter = new BufferedOutputStream(fos);

    while ((count = fileReader.read(bytes)) > 0) {
        toServer.write(bytes, 0, count);
        total_received = 0;
        while(total_received < count) {
            incount = fromServer.read(inbytes);
            total_received += incount;
            fileWriter.write(inbytes, 0, incount);
        }
    }
    toServer.close(); //to break the while loop on server
    incount = fromServer.read(inbytes);
    System.out.println(incount);

服务器:

    while ((count = fromClient.read(bytes)) > 0) 
    {
       //processedBytes
        toClient.write(processedBytes, 0, count);
    }
    toClient.write("Process done!".getBytes(), 0, "Process done!".length());
    toClient.flush();

问题:

文件正在成功传输.....但是客户端未接收到处理文件后的消息....我在计算机上收到 java.net.SocketException:套接字已关闭客户端.我了解到,当客户端仍在监听并引发SocketException时,套接字在服务器端已关闭.但是服务器中的 toClient.write()语句会怎样?

The file is being transferred successfully.....but the message after processing the file is not being received by the client....i get java.net.SocketException: Socket closed on the client side. I understand that the socket gets closed on the server side while the client is still listening bringing up the SocketException. But what happens to the toClient.write() statement in the server?

谢谢.

推荐答案

您也不应该调用 toServer.close(),因为它也会关闭套接字.如果要中断服务器上的while循环,则需要发送一些特殊字符(例如SOH字符),可以在服务器端进行搜索,并且一旦服务器获得终止,它将终止循环并将ack发送回客户端,然后客户端可以关闭套接字.

You should not call toServer.close() as it closes the socket as well. If you want to break the while loop on server you need to send some special character like SOH character which could be searched on server side and as soon as server gets that it terminates the loop and sends the ack back to client and then client can close the socket.

这篇关于发送文件后通过套接字发送文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆