简体   繁体   English

如何将用户的字符串数据作为字节数组写入套接字

[英]How to write the string data from user as byte array to socket

I have a class that receives messages sent by the user and prints them out on the terminal, but now I am trying to write a class that reads data from the user, converts the string data from the user into an array of bytes, and write the byte array to the socket.我有一个类可以接收用户发送的消息并将它们打印在终端上,但是现在我正在尝试编写一个从用户读取数据的类,将来自用户的字符串数据转换为字节数组,然后写入字节数组到套接字。

I am trying to read data from the user using BufferedReader and write the byte array to the socket using OutputStream, but for some reason, the message that I am writing to the socket isn't delivered to the server.我正在尝试使用 BufferedReader 从用户读取数据并使用 OutputStream 将字节数组写入套接字,但由于某种原因,我写入套接字的消息未传递到服务器。

BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String newLine = r.readLine();
while (r.ready() && newLine != null) {

    // TODO: read data from the user, blocking until ready. Convert the
    //string data from the user into an array of bytes and write
    //the array of bytes to "socket".

    byte[] message = newLine.getBytes();
    OutputStream outputStream = s.getOutputStream();
    outputStream.write(message);
}

s is the socket with the same server and port number as the one I am sending it to! s是与我将其发送到的具有相同服务器和端口号的套接字!

There are no errors when I run this, so I genuinely have no idea why this won't send the message to the socket.运行它时没有错误,所以我真的不知道为什么这不会将消息发送到套接字。

String newLine = r.readLine();

Perhaps you misunderstand how java works;也许你误解了java是如何工作的; your confusion is logical only if you believe that this sets up a sort of alias: That everytime newLine is so much as touched, that it's just a shorthand for r.readLine() .只有当您认为这设置了一种别名时,您的困惑才合乎逻辑:每次newLine被触及,它只是r.readLine()的简写。

That is not how java works.这不是java的工作方式。 You read a line from r exactly once in this code, at the very start, and never again.您在这段代码中从r读取了一行,从开始,就再也没有了。 That line above means: Execute r.readLine() right this very moment, allow that method to put the string it gets someplace in memory, and then have newLine be an alias for that string , not for the general idea of 'pull another string off of the network buffers'.上面那行的意思是:就在r.readLine()执行r.readLine() ,允许该方法将它获取的字符串放在内存中的某个位置,然后让newLine成为该字符串的别名,而不是“拉另一个字符串”的一般想法关闭网络缓冲区'。

r.readLine() needs to be somewhere in that loop. r.readLine()需要在该循环中的某个位置。

More generally, don't call .ready() , it's not useful.更一般地,不要调用.ready() ,它没有用。 Call readLine() only.仅调用readLine() Calling that will 'block' until data is available automatically, and will return null when no more data will ever come (because the connection has been closed).调用它将“阻塞”直到数据自动可用,并且在没有更多数据到来时将返回null (因为连接已关闭)。

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

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