简体   繁体   English

如何使用Java中的SocketChannel发送然后读取\\ n

[英]how to send and then read \n using SocketChannel in Java

I am using the SocketChannel Java class for a client/server application. 我使用SocketChannel Java类作为客户端/服务器应用程序。 I can send and retrieve data. 我可以发送和检索数据。 But if my data contains '\\n' then I do not read the correct data. 但如果我的数据包含'\\n'那么我就不会读取正确的数据。 For example 例如

sending data = "Hi dear"
receiving data = "Hi dear"

sending data = "Hi dear\n\n i am fine"
receiving data = "Hi dear"

sending data = "Hi dear\\n\\n i am fine"
receiving data = "Hi dear\n\n i am fine"


ByteBuffer byteBuffer = ByteBuffer.allocate(BUFSIZE);
int nbytes = socketChannel.getChannel().read(byteBuffer);

I am using US-ASCII decoding. 我正在使用US-ASCII解码。 How can I overcome this type of problem? 我怎样才能克服这类问题?

Thanks, Deepak 谢谢,迪帕克

The read operation doesn't guarantee to read all of the available data, nor read any data at all if the SocketChannel is in non blocking mode. 如果SocketChannel处于非阻塞模式,则读操作不保证读取所有可用数据,也不保证读取任何数据。 In the case above, you may need more than one call to read all of the data transmitted. 在上面的情况中,您可能需要多次调用才能读取所有传输的数据。

You need some sort of way for the receiving code to know when it has read all of the data. 您需要某种方式让接收代码知道它何时读取了所有数据。 This means either having the sender send information about the content of the data (length etc.) as part of an agreed protocol, or by using the Channel for only one chunk of data and reading the Channel until it is closed. 这意味着让发送方发送有关数据内容的信息(长度等)作为约定协议的一部分,或者通过仅将信道用于一个数据块并读取信道直到它关闭。

I think you're having an issue with the ByteBuffer on the allocation. 我认为你在分配时遇到了ByteBuffer的问题。

I've had issues previously with SocketChannel where data just seemed to get held up. 我之前遇到过SocketChannel的问题,数据似乎已经被搁置了。 I would recommend doing some sysouts on ByteBuffer 我建议在ByteBuffer上做一些sysout

while(ByteBuffer.hasRemaining(){
    socketChannel.write(buffer) //writing data
    System.out.printline(socketChanel.remaining() + " : bytes to go");
}

This may be a step in the right direction to isolating the issue. 这可能是朝着解决问题的正确方向迈出的一步。

If you are sending data as binary as you suggest, there is no reason that \\n would be treated differently to any other byte. 如果您按照建议以二进制形式发送数据,则没有理由将n与任何其他字节区别对待。 If it were things like images would get corrupted all the time. 如果像图像那样的东西会一直被破坏。 The encoding shouldn't make any difference if you have using characters <= 127. 如果您使用字符<= 127,编码应该没有任何区别。

I would suggest your application isn't working the way you think it is and that you are reading strings which assume a \\n termination somewhere in your code. 我建议您的应用程序不按照您认为的方式运行,并且您正在读取字符串,这些字符串假设在代码中的某处终止。

Can you post the code for writing and reading the string. 你可以发布用于编写和读取字符串的代码。 ie how do you determine when the string ends? 即如何确定字符串何时结束?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM