Java TCP socket program to send and read [x] bytes array. How to loop, sout and sent correctly

huangapple go评论47阅读模式
英文:

Java TCP socket program to send and read [x] bytes array. How to loop, sout and sent correctly

问题

我是你的中文翻译,以下是翻译好的内容:

问题描述:
我对套接字和编写基本的Java客户端到服务器到客户端程序还很陌生。在这种情况下,我发送消息的长度 outToServer.writeInt(message.length); 以及数组 byte[] message = new byte[10]; 到服务器,服务器读取并将其打印到控制台,然后修改数组中的一些字节,然后将其发送回客户端。客户端接收数组,读取它并将其打印到控制台。

问题是它只打印:

从服务器接收的字节数组类:

0
0
0
0
0
0
0
0
0
0
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

然而,它应该打印一些经过修改的带有不同数字的字节。

我认为在 for 循环或接收字节部分存在问题。我是否应该使用 readFully 或类似的方法,以正确地循环我想要的值?

非常感谢。

客户端:

class TCPClient2 {

    public static void main(String argv[])
    {

        try {
            System.out.println("Client started");
            Socket clientSocket = new Socket("localhost", 8080);
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
            System.out.println("\n发送到服务器之前打印的字节数组:");

            byte[] message = new byte[10];
            //byte[] message = new byte[] { -1, -128, 1, 127, 23, 23, 23, 23, 23, 10 }; // 也可以尝试这些
            message[0] = 1; // 更改数组的第一个字节


            for(int i = 0; i < message.length; i++) {
                System.out.println(message[i]);     // 打印发送到服务器之前的字节数组
            }
            System.out.println(Arrays.toString(message)); // 打印发送到服务器之前的字节数组作为字符串
            System.out.println("\n");


            outToServer.writeInt(message.length); // 写入消息的长度
            outToServer.write(message);           // 写入消息
            //
            //
            // 消息数组现在已发送到服务器
            //
            // 等待答案
            //


            // 现在从服务器接收答案
            System.out.println("从服务器接收的字节数组:");
            DataInputStream inFromClient = new DataInputStream(clientSocket.getInputStream());


            int length = inFromClient.readInt(); // 读取传入消息的长度
                    /*
                    if(length > 0) {
                        byte[] message = new byte[length];
                        dIn.readFully(message, 0, message.length); // 读取消息
                    }
                        */

            byte[] messageFromServer = new byte[length];
            for(int i = 0; i < messageFromServer.length; i++) {
                System.out.println(messageFromServer[i]);// 打印接收到的字节数组
            }
            System.out.println(Arrays.toString(messageFromServer));// 打印接收到的字节数组作为字符串

        }catch (Exception e) {
            e.printStackTrace();
        }


    }

}

服务器:

class TCPServer2 {

    public static void main(String argv[])
    {

                try
                {
                    System.out.println("等待连接");
                    ServerSocket welcomeSocket = new ServerSocket(8080);
                    Socket connectionSocket = welcomeSocket.accept();
                    System.out.println("连接已建立");

                    DataInputStream inFromClient =
                            new DataInputStream(connectionSocket.getInputStream());         // 从客户端接收字节数组

                    int length = inFromClient.readInt(); // 读取传入消息的长度
                    /*
                    if(length > 0) {
                      byte[] message = new byte[length];
                        inFromClient.readFully(message, 0, message.length); // readFully 消息,但如何做?
                    }
                    */

                    byte[] message = new byte[length];
                    for(int i = 0; i < message.length; i++) {
                        System.out.println(message[i]); // 打印数组
                    }

                    System.out.println(Arrays.toString(message)); // 以字符串形式打印数组
                    System.out.println("来自客户端的消息已打印");

                    message[0]= 1;      // 更改接收到的数组的字节
                    message[9]=1;       // 更改接收到的数组的字节

                    DataOutputStream outToClient =
                            new DataOutputStream(connectionSocket.getOutputStream()); // 将带有更改的字节数组发送回客户端

                    outToClient.writeInt(message.length); // 写入消息的长度
                    outToClient.write(message);           // 写入消息

                    System.out.println("已发送消息给客户端");



                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

    }
英文:

I'm new with sockets and writing basic Java Client-to-Server-to-Client program that sends in this case
length of the message outToServer.writeInt(message.length); and byte[] message = new byte[10]; array to Server that reads and prints it to console and then modifies few bytes in the array and then sends it back to the Client. Client receives the array, reads it and and prints it to console.

My problem is that it prints only:

byte array received from server class: 
0
0
0
0
0
0
0
0
0
0
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

when it should print some modified bytes with different numbers.

I assume there's some problem with for loop or in the reading part of the received bytes. Should i use readFully or something similar and how to do it correctly to loop the values i want?

Many thanks.

Client:

class TCPClient2 {
public static void main(String argv[])
{
try {
System.out.println(&quot;Client started&quot;);
Socket clientSocket = new Socket(&quot;localhost&quot;, 8080);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
System.out.println(&quot;\nByte array printed before sending to server:\n&quot;);
byte[] message = new byte[10];
//byte[] message = new byte[] { -1, -128, 1, 127, 23, 23, 23, 23, 23, 10 }; // you can try these too
message[0] = 1; // changes the first byte of the array
for(int i = 0; i &lt; message.length; i++) {
System.out.println(message[i]);     //prints byte array BEFORE being sent to server
}
System.out.println(Arrays.toString(message)); //prints byte array BEFORE being sent to server as String
System.out.println(&quot;\n&quot;);
outToServer.writeInt(message.length); // write length of the message
outToServer.write(message);           // write the message
//
//
// Message -array is now sent to Server
//
// Waiting for answer
//
// Answer is now received from Server
System.out.println(&quot;byte array received from server class: \n&quot;);
DataInputStream inFromClient = new DataInputStream(clientSocket.getInputStream());
int length = inFromClient.readInt(); // read length of incoming message
/*
if(length&gt;0) {
byte[] message = new byte[length];
dIn.readFully(message, 0, message.length); // read the message
}
*/
byte[] messageFromServer = new byte[length];
for(int i = 0; i &lt; messageFromServer.length; i++) {
System.out.println(messageFromServer[i]);//prints received byte array
}
System.out.println(Arrays.toString(messageFromServer));//prints received byte array as a string
}catch (Exception e) {
e.printStackTrace();
}
}
}

Server:

class TCPServer2 {
public static void main(String argv[])
{
try
{
System.out.println(&quot;waiting for connections&quot;);
ServerSocket welcomeSocket = new ServerSocket(8080);
Socket connectionSocket = welcomeSocket.accept();
System.out.println(&quot;connection established&quot;);
DataInputStream inFromClient =
new DataInputStream(connectionSocket.getInputStream());         //receive byte array from client
int length = inFromClient.readInt(); // read length of incoming message
/*
if(length&gt;0) {
byte[] message = new byte[length];
inFromClient.readFully(message, 0, message.length); // readFully the message, but how?
}
*/
byte[]message = new byte[length];
for(int i = 0; i &lt; message.length; i++) {
System.out.println(message[i]); // print array
}
System.out.println(Arrays.toString(message)); // print array as string
System.out.println(&quot;message from client printed&quot;);
message[0]= 1;      //change bytes of the received array
message[9]=1;       //change bytes of the received array
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream()); //send byte array with changes back to the client
outToClient.writeInt(message.length); // write length of the message
outToClient.write(message);           // write the message
System.out.println(&quot;message to client sent&quot;);
} catch (Exception e) {
e.printStackTrace();
}
}
}

答案1

得分: 0

问题在于您没有从套接字中读取数据,而只是循环遍历了本地数组。

您需要更改以下代码部分:

1) 服务器

从:

byte[] message = new byte[length];
for(int i = 0; i &lt; message.length; i++) {
    System.out.println(message[i]); // 打印数组
}

到:

byte[] message = new byte[length];
for(int i = 0; i &lt; message.length; i++) {
    message[i] = inFromClient.readByte();
    System.out.println(message[i]); // 打印数组
}

2) 客户端

从:

byte[] messageFromServer = new byte[length];
for(int i = 0; i &lt; messageFromServer.length; i++) {
    System.out.println(messageFromServer[i]);//打印接收到的字节数组
}

到:

byte[] messageFromServer = new byte[length];
for(int i = 0; i &lt; messageFromServer.length; i++) {
    messageFromServer[i] = inFromClient.readByte();
    System.out.println(messageFromServer[i]);//打印接收到的字节数组
}

一个例子是没有指定控件,数组的长度等等...

或者使用您的readFully函数

1) 服务器

int length = inFromClient.readInt(); // 读取传入消息的长度
byte[] message = new byte[length];
if (length &gt; 0) {
    inFromClient.readFully(message, 0, message.length); // readFully消息,但怎么做?
}

for (int i = 0; i &lt; message.length; i++) {
    System.out.println(message[i]); // 打印数组
}

2) 客户端

int length = inFromClient.readInt(); // 读取传入消息的长度
byte[] messageFromServer = new byte[length];
if (length &gt; 0) {
    inFromClient.readFully(messageFromServer, 0, messageFromServer.length); // 读取消息
}

for (int i = 0; i &lt; messageFromServer.length; i++) {
    System.out.println(messageFromServer[i]);//打印接收到的字节数组
}
英文:

The problem is that you did not read the data from the socket, but only cycled through the local array.

You need to change these pieces of code:

1) Server

from:

            byte[]message = new byte[length];
for(int i = 0; i &lt; message.length; i++) {
System.out.println(message[i]); // print array
}

to:

            byte[]message = new byte[length];
for(int i = 0; i &lt; message.length; i++) {
message[i] = inFromClient.readByte();
System.out.println(message[i]); // print array
}

2) client

from:

    byte[] messageFromServer = new byte[length];
for(int i = 0; i &lt; messageFromServer.length; i++) {
System.out.println(messageFromServer[i]);//prints received byte array
}

to:

    byte[] messageFromServer = new byte[length];
for(int i = 0; i &lt; messageFromServer.length; i++) {
messageFromServer[i] = inFromClient.readByte();
System.out.println(messageFromServer[i]);//prints received byte array
}

An example is without specifying controls, the length of the array, ...

Or with your function readFully

1) Server

    int length = inFromClient.readInt(); // read length of incoming message
byte[] message = new byte[length];
if (length &gt; 0) {
inFromClient.readFully(message, 0, message.length); // readFully the message, but how?
}
for (int i = 0; i &lt; message.length; i++) {
System.out.println(message[i]); // print array
}

2) Client

    int length = inFromClient.readInt(); // read length of incoming message
byte[] messageFromServer = new byte[length];
if (length &gt; 0) {
inFromClient.readFully(messageFromServer, 0, messageFromServer.length); // read the message
}
for (int i = 0; i &lt; messageFromServer.length; i++) {
System.out.println(messageFromServer[i]);//prints received byte array
}

huangapple
  • 本文由 发表于 2020年7月30日 18:48:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63171545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定