I have designed a Java Client class that is required to send a byte[] array to a Java Server class via a socket. Here is my code:
我设计了一个Java客户端类,它需要通过套接字将一个byte[]数组发送到Java服务器类。这是我的代码:
ByteArrayClient.java
ByteArrayClient.java
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ByteArrayClient {
public static void main(String[] args) {
//make POJO__________________________
ByteEncodeSubscriptionReq sr1=ByteEncodeSubscriptionReq.makeRequest(103, "Str1", "Str2");
//Connection details____________________
String serverName = "localhost";
int port = 6060;
try {
//Establish Connection with server_______________________________
System.out.println("ByteArrayClient: Connecting to " + serverName +":" + port+"...");
Socket client = new Socket(serverName, port);//make new socket
System.out.println("ByteArrayClient: connected to " + client.getRemoteSocketAddress());
//Encode POJO to ByteArray________________________________
byte[] SubscripReqByteArray=ByteEncodeSubscriptionReq.encode(sr1);
//encoded correctly to a 44 bit byte array
System.out.println("ByteArrayClient: SubscripTionRequest successfully encoded");
//Send POJO ByteArray to server__________________________
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.write(SubscripReqByteArray);;
System.out.println("ByteArrayClient: POJO sent to server");
//Receive Server response_________________________________
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("ByteArrayClient received: " + in.readUTF());
//close socket____________________________________
client.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("PojoClient: Connection Failed");
}
}
}
...and ByteArrayServer.java
…和ByteArrayServer.java
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class ByteArrayServer extends Thread{
private ServerSocket serverSocket;
public ByteArrayServer(int port) throws IOException {
serverSocket = new ServerSocket(port);//create server socket
serverSocket.setSoTimeout(15000);//socket closes after 15 seconds
this.start();
}
public void run() {
while (true) {//server runs infinitely______________
try {
System.out.println("ByteArrayServer: Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket servedClient = serverSocket.accept();//client socket
System.out.println("ByteArrayServer: connected to " + servedClient.getRemoteSocketAddress());
//Receive Client ByteArray___________________________________________
ByteEncodeSubscriptionReq receivedReq=new ByteEncodeSubscriptionReq();//server side POJO
System.out.println("ByteArrayServer: created SubscriptionReq Object");
InputStream PojoStreamHolder = servedClient.getInputStream();
System.out.println("ByteArrayServer: client InputStream received");
byte[] clientByteStream=new byte[44];//same size as Pojo byte requirement
_____/*MY CODE IS STUCK SOMEWHERE HERE*/__________
servedClient.getInputStream().read(clientByteStream);
System.out.println("ByteArrayServer: clientByteStream received: "+clientByteStream[0]+" "+clientByteStream[1]);
receivedReq=ByteEncodeSubscriptionReq.decode(clientByteStream);
//Send confirmation to Client__________________________________________________
DataOutputStream out = new DataOutputStream(servedClient.getOutputStream());
if(receivedReq.getRequestSymbol().trim().length()!=0){
out.writeUTF("ByteArrayServer received Subscription ID="+receivedReq.getSubscriptionID());
System.out.println("ByteArrayServer: new SubscriptionRequest ID="+receivedReq.getSubscriptionID()+" Subscriber_Name="+receivedReq.getSubscriberName());
}else{
out.writeUTF("ByteArrayServer: did not receive Subscription ID");
}
//Close Client socket_________________________________________________________
//server.close();
//serverSocket.close();
} catch (SocketTimeoutException s) {
System.out.println("PojoServer: Socket timed out after " + getTimeElapsedInSeconds(startTime) + " seconds from start");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
// int port = Integer.parseInt(args[0]);//to get port as an Argument
int port = 6060;
try {
Thread t = new ByteArrayServer(port);
startTime = System.currentTimeMillis();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is the Server console output:
这里是服务器控制台输出:
ByteArrayServer: Waiting for client on port 6060...
ByteArrayServer: connected to /127.0.0.1:64233
ByteArrayServer: created SubscriptionReq Object
ByteArrayServer: client InputStream received
The issue is that while the Stream is received by the server without errors, it gets stuck near servedClient.getInputStream().read(clientByteStream); method and does not proceed further.
问题是,虽然服务器接收到的流没有错误,但它会被卡在servedClient.getInputStream().read(clientByteStream)上;方法并没有进一步进行。
I've also tried
我也试过
int count=servedClient.getInputStream().read(clientByteStream);
and
和
DataInputStream in = new DataInputStream(servedClient.getInputStream());
long bStr=in.readLong();
and
和
ObjectInputStream PojoObjHolder = new ObjectInputStream(PojoStreamHolder);
byte[] clientByteStream2 = (byte[])PojoObjHolder.readObject();
..but they show the same problem as well.
. .但是他们也有同样的问题。
How should I pass the Byte Array between the two classes without extra imports?
如果没有额外的导入,我应该如何在两个类之间传递字节数组?
2 个解决方案
#1
0
The problem was in my ByteArrayClient Class. I had to link the OutputStream with the client socket, rather than creating a new instance of it. So I replaced:
问题是在我的ByteArrayClient类中。我必须将OutputStream与客户机套接字连接起来,而不是创建一个新的实例。所以我代替:
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.write(SubscripReqByteArray);;
with
与
OutputStream os = client.getOutputStream(out);
os.write(SubscripReqByteArray);;
Thank you for the hint Ekant
谢谢你的提示。
#2
0
DataInputStream.readFully(byte[] b)
will finish only when in inputstream bytes till b.length available. So for sure you need to debug if you have all the bytes or not.And the solution is to make those byte available so that the function will finish. Same for DataInputStream.read(byte[] b) The method is blocked until input data is available. Please make sure by debugging your app that inputstream have 44 bytes. Try below to count available bytes and you can read those easily.
DataInputStream。readFully(字节[]b)将只在输入流字节中完成,直到b。长度可用。因此,如果你有所有的字节,你肯定需要进行调试。解决方案是使这些字节可用以使函数完成。DataInputStream相同。读取(字节[]b)方法被阻塞,直到输入数据可用为止。请调试你的应用程序,inputstream有44个字节。下面尝试计算可用字节,您可以轻松阅读这些字节。
// count the available bytes form the input stream int count = is.available();
//计算输入流int count = is.available()的可用字节数;
// create buffer
byte[] bs = new byte[count];
// read data into buffer
dis.read(bs);
#1
0
The problem was in my ByteArrayClient Class. I had to link the OutputStream with the client socket, rather than creating a new instance of it. So I replaced:
问题是在我的ByteArrayClient类中。我必须将OutputStream与客户机套接字连接起来,而不是创建一个新的实例。所以我代替:
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.write(SubscripReqByteArray);;
with
与
OutputStream os = client.getOutputStream(out);
os.write(SubscripReqByteArray);;
Thank you for the hint Ekant
谢谢你的提示。
#2
0
DataInputStream.readFully(byte[] b)
will finish only when in inputstream bytes till b.length available. So for sure you need to debug if you have all the bytes or not.And the solution is to make those byte available so that the function will finish. Same for DataInputStream.read(byte[] b) The method is blocked until input data is available. Please make sure by debugging your app that inputstream have 44 bytes. Try below to count available bytes and you can read those easily.
DataInputStream。readFully(字节[]b)将只在输入流字节中完成,直到b。长度可用。因此,如果你有所有的字节,你肯定需要进行调试。解决方案是使这些字节可用以使函数完成。DataInputStream相同。读取(字节[]b)方法被阻塞,直到输入数据可用为止。请调试你的应用程序,inputstream有44个字节。下面尝试计算可用字节,您可以轻松阅读这些字节。
// count the available bytes form the input stream int count = is.available();
//计算输入流int count = is.available()的可用字节数;
// create buffer
byte[] bs = new byte[count];
// read data into buffer
dis.read(bs);