java 通过套接字发送多个字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5827196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sending multiple byte array over the socket
提问by Programming_Lover
I want to send multiple byte array from the client and server ?
我想从客户端和服务器发送多个字节数组?
I was able to send/Receive one byte array from client and send / Receive one byte array from server :
我能够从客户端发送/接收一个字节数组并从服务器发送/接收一个字节数组:
My code is like this :
我的代码是这样的:
server :
服务器 :
Socket sock=null;
ByteArrayOutputStream input=null;
OutputStream out=null;
InputStream in=null;
try{
ServerSocket server_sock=new ServerSocket(2972);
sock=server_sock.accept();
in =
sock.getInputStream();
out=sock.getOutputStream();
}catch(IOException e){
System.out.println(e.getMessage());
}
String word="";
//1-Receive
try{
ByteArrayOutputStream serverinput=new ByteArrayOutputStream();
int len=0;
byte[] buf=new byte[1000];
while ((len = in.read(buf))>=0) {
serverinput.write(buf, 0, len);
}
sock.shutdownInput();
word=new String(serverinput.toByteArray());
System.out.println("Client send 1"+word);
}catch(Exception e){
System.out.println(e.getMessage());
}
String st="Server is a king";
try{
out.write(st.getBytes());
out.flush();
}catch(Exception e){
System.out.println(e.getMessage());
}
client :
客户 :
Socket sock=null;
OutputStream out=null;
InputStream in=null;
try{
sock=new Socket("127.0.0.1",2972);
}catch(IOException e){
System.out.println(e.getMessage());
}
String word="Hellow World" ;
try{
in =
sock.getInputStream();
out=sock.getOutputStream();
}catch(IOException e){
System.out.println(e.getMessage());
}
//1- send
try{
System.out.println("Your string is"+word+"converted to byte"+word.getBytes());
out.write(word.getBytes());
out.flush();
sock.shutdownOutput();
}catch(Exception e){
System.out.println(e.getMessage());
}
try{ ByteArrayOutputStream serverinput=new ByteArrayOutputStream();
int len=0;
byte[] buf=new byte[1000];
while ((len = in.read(buf))>=0) {
serverinput.write(buf, 0, len);
}
System.out.println("server send 1 "+new String(serverinput.toByteArray()));
System.out.println("Your string is"+word+"converted to byte"+word.getBytes());
}catch(Exception e){
System.out.println(e.getMessage());
}
This code is working fine for one submitting from client and server but it does not work when I want to send / receive more byte array ?
此代码对于从客户端和服务器提交的代码工作正常,但是当我想发送/接收更多字节数组时它不起作用?
It is working only when I use shutdown because both client and server reading and writing to the data.
它仅在我使用关闭时才有效,因为客户端和服务器都在读取和写入数据。
Therefore, I can not use the socket channel again ... is there is alternative solution? ...that does not lead to deadlock.
因此,我不能再次使用套接字通道......是否有替代解决方案?...这不会导致僵局。
回答by Stephen C
The problem you have is that you don't currently have any way to say when one byte array ends and the next one starts. (In your "one array" solution, the end of the byte array corresponds to the end of stream. And of course, once the stream has been ended / closed, it cannot be reopened without creating a new Socket
, etcetera.)
您遇到的问题是您目前无法确定一个字节数组何时结束和下一个字节数组何时开始。(在您的“一个数组”解决方案中,字节数组的结尾对应于流的结尾。当然,一旦流结束/关闭,如果不创建新的Socket
等,就无法重新打开它。)
The simple way to solve this is as follows, using DataOutputStream and DataInputStream pairs wrapped around the respective socket streams:
解决这个问题的简单方法如下,使用包裹在相应套接字流上的 DataOutputStream 和 DataInputStream 对:
To send a byte array:
Convert data to bytes.
Send the byte array size using the
DataOutputStream.writeInt(int)
method.Send the byte array using
DataOutputStream.write(byte[])
method.
To receive a byte array:
Receive the byte array size using the
DataInputStream.readInt()
method.Allocate a byte array of the required size.
Receive the bytes into the byte array using the
DataInputStream.read(byte[], int, int)
method ... repeatedly until you've gotten all of the bytes.
发送字节数组:
将数据转换为字节。
使用
DataOutputStream.writeInt(int)
方法发送字节数组大小。使用
DataOutputStream.write(byte[])
方法发送字节数组。
接收字节数组:
使用
DataInputStream.readInt()
方法接收字节数组大小。分配所需大小的字节数组。
使用该
DataInputStream.read(byte[], int, int)
方法将字节接收到字节数组中...重复,直到获得所有字节。
By sending the size of the byte array at the front, you tell the receiver how many bytes to read. You can repeat this process as many times as you need. The sender can indicate to the receiver that there are no more byte arrays to send by simply closing the socket stream.
通过在前面发送字节数组的大小,您告诉接收方要读取多少字节。您可以根据需要多次重复此过程。发送方可以通过简单地关闭套接字流向接收方指示没有更多的字节数组要发送。
Note - this is pseudo-code. I assume that you are capable of turning it into working Java.
注意 - 这是伪代码。我假设你有能力把它变成可用的 Java。
Don't forget to insert BufferedInputStreams and BufferedOutputStreams into the respective stream chains ... to reduce system call overheads.
不要忘记将 BufferedInputStreams 和 BufferedOutputStreams 插入到各自的流链中……以减少系统调用开销。
回答by Ted Hopp
Try wrapping your socket streams in DataInputStream and DataOutputStream. That should allow you to do what you want.
尝试将您的套接字流包装在 DataInputStream 和 DataOutputStream 中。这应该允许你做你想做的事。
回答by sgokhales
You should really have a look at this tutorial : Reading from and Writing to a Socket
你真的应该看看这个教程:Reading from and Writing to a Socket
It seems to outline how to read and write to a socket. The reading should be as easy as creating a server socket and listening on the port you expect and then waiting for data.
它似乎概述了如何读取和写入套接字。读取应该像创建服务器套接字并侦听您期望的端口然后等待数据一样简单。
回答by Cris CodeCruncher
You could also create an object that would hold your byte array and send it out with ObjectOutputStream
, then use the writeObject(Object)
method to send the info.
您还可以创建一个对象来保存您的字节数组并使用 将其发送出去ObjectOutputStream
,然后使用该writeObject(Object)
方法发送信息。