gpt4 book ai didi

java - 是否可以在服务器上解码从客户端作为字节数组发送的字节?

转载 作者:行者123 更新时间:2023-12-01 13:31:11 25 4
gpt4 key购买 nike

我只是想测试通过 TCP 套接字连接发送字节,我知道这并不是真正的目的,但我只是想弄清楚这是否可能

我正在尝试做什么:

  • 从客户端上的字符串获取字节

  • 将其作为字节发送到服务器

  • 获取服务器上的字节并将其解码回原始字符串

客户:

package ByteClientServer;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.*;

public class Client {


String hostAddress = "localhost";
int port = 1010;


public Client()
{
try {

Socket socket = new Socket(hostAddress, port);

String test = "hello"; //dycrypt bytes from this string on server side

byte[] byteArray = test.getBytes();

OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);

dos.write(byteArray);

}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}


public static void main(String[] args)
{
new Client();
}




}

服务器:

package ByteClientServer;

import java.io.*;
import java.net.*;


public class Server {

public static void main(String[] args)
{
try
{
ServerSocket server = new ServerSocket(1010);
server.setSoTimeout(0);

Socket connectionToClient = server.accept();
InputStream is = connectionToClient.getInputStream();
DataInputStream dis = new DataInputStream(is);


byte[] data = dis.readUTF().getBytes();

//dis.readFully(data, 0, data.length);

String s = new String(data);

System.out.println(s);


}
catch(IOException e)
{
e.printStackTrace();
//System.err.println("Server was terminated.");
}
}
}

它不喜欢服务器上的这一行:

byte[] data = dis.readUTF().getBytes();

并抛出异常:

java.net.SocketException: Connection reset at java.net.SocketInputStream.read(Unknown Source) at java.net.SocketInputStream.read(Unknown Source) at java.io.DataInputStream.readFully(Unknown Source) at java.io.DataInputStream.readUTF(Unknown Source) at java.io.DataInputStream.readUTF(Unknown Source) at ByteClientServer.Server.main(Server.java:21)

最佳答案

如果您想使用readUTF,那么您需要使用writeUTF。如果您只想写入字节,那么您只需读取字节。

关于java - 是否可以在服务器上解码从客户端作为字节数组发送的字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21560828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com