我想送,虽然插座不止一个随机值。 我认为阵列是送them..But我不知道如何写一个数组的Socket的OutputStream的最佳方式?
我的Java类
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.io.*;
import java.util.Random;
class NodeCommunicator {
public static void main(String[] args) {
try {
Socket nodejs = new Socket("localhost", 8181);
Random randomGenerator = new Random();
for (int idx = 1; idx <= 1000; ++idx){
Thread.sleep(500);
int randomInt = randomGenerator.nextInt(35);
sendMessage(nodejs, randomInt + " ");
System.out.println(randomInt);
}
while(true){
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println("Connection terminated..Closing Java Client");
System.out.println("Error :- "+e);
}
}
public static void sendMessage(Socket s, String message) throws IOException {
s.getOutputStream().write(message.getBytes("UTF-8"));
s.getOutputStream().flush();
}
}
Answer 1:
使用java.io.DataOutputStream中/ DataInputStream所对,他们知道如何阅读整数。 发送信息的长度+随机数的包。
寄件人
Socket sock = new Socket("localhost", 8181);
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
out.writeInt(len);
for(int i = 0; i < len; i++) {
out.writeInt(randomGenerator.nextInt(35))
...
接收器
DataInputStream in = new DataInputStream(sock.getInputStream());
int len = in.readInt();
for(int i = 0; i < len; i++) {
int next = in.readInt();
...
Answer 2:
Java数组实际上是Object
S和此外,他们实现Serializable
接口。 所以,你可以序列化您的数组,得到字节,并把这些通过套接字。 这应该这样做:
public static void sendMessage(Socket s, int[] myMessageArray)
throws IOException {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bs);
os.writeObject(myMessageArray);
byte[] messageArrayBytes = bs.toByteArray();
s.getOutputStream().write(messageArrayBytes);
s.getOutputStream().flush();
}
什么是真正整洁的这个是,它不仅为int[]
但对于任何Serializable
对象。
编辑:关于它又在想,这是更简单:
发件人 :
public static void sendMessage(Socket s, int[] myMessageArray)
throws IOException {
OutputStream os = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(myMessageArray);
}
接收器 :
public static int[] getMessage(Socket s)
throws IOException {
InputStream is = s.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
int[] myMessageArray = (int[])ois.readObject();
return myMessageArray;
}
我要离开我的第一个问题的答案也因为(它也可以和),它是写对象UDP有用DatagramSockets
和DatagramPackets
那里没有流。
Answer 3:
我会建议简单地串联了int
使用一些分隔符例如,在一个字符串值@@
,然后同时发送的最后串联的字符串。 在接收端,只是用相同的分隔符来获得分割字符串int[]
回例如:
Random randomGenerator = new Random();
StringBuilder numToSend = new StringBuilder("");
numToSend.append(randomGenerator.nextInt(35));
for (int idx = 2; idx <= 1000; ++idx){
Thread.sleep(500);
numToSend.append("@@").append(randomGenerator.nextInt(35));
}
String numsString = numToSend.toString();
System.out.println(numsString);
sendMessage(nodejs, numsString);
在接收端,让您的字符串分割为:
Socket remotejs = new Socket("remotehost", 8181);
BufferedReader in = new BufferedReader(
new InputStreamReader(remotejs.getInputStream()));
String receivedNumString = in.readLine();
String[] numstrings = receivedNumString.split("@@");
int[] nums = new int[numstrings.length];
int indx = 0;
for(String numStr: numstrings){
nums[indx++] = Integer.parseInt(numStr);
}
Answer 4:
那么,甲流是一个字节流,所以你必须将数据编码成字节序列,并在接收端进行解码。 怎样写数据取决于你想如何编码。
如在单一的字节从0到34的数字拟合,这可以是那么容易,因为:
outputStream.write(randomNumber);
而在另一边:
int randomNumber = inputStream.read();
当然,每一个字节后刷新流不是很有效(因为它会生成每个字节的网络数据包,每个网络数据包中包含数十个头和路由信息...字节)。 如果性能的事情,你可能会想使用的BufferedOutputStream了。
Answer 5:
所以,你可以比较其他格式我写了一个模板,它允许你使用任何格式的愿望,或比较的替代品。
abstract class DataSocket implements Closeable {
private final Socket socket;
protected final DataOutputStream out;
protected final DataInputStream in;
DataSocket(Socket socket) throws IOException {
this.socket = socket;
out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void writeInts(int[] ints) throws IOException {
writeInt(ints.length);
for (int i : ints)
writeInt(i);
endOfBlock();
}
protected abstract void writeInt(int i) throws IOException;
protected abstract void endOfBlock() throws IOException;
public int[] readInts() throws IOException {
nextBlock();
int len = readInt();
int[] ret = new int[len];
for (int i = 0; i < len; i++)
ret[i] = readInt();
return ret;
}
protected abstract void nextBlock() throws IOException;
protected abstract int readInt() throws IOException;
public void close() throws IOException {
out.close();
in.close();
socket.close();
}
}
二进制格式,4个字节的整数
class BinaryDataSocket extends DataSocket {
BinaryDataSocket(Socket socket) throws IOException {
super(socket);
}
@Override
protected void writeInt(int i) throws IOException {
out.writeInt(i);
}
@Override
protected void endOfBlock() throws IOException {
out.flush();
}
@Override
protected void nextBlock() {
// nothing
}
@Override
protected int readInt() throws IOException {
return in.readInt();
}
}
每7位的一个字节停止位编码的二进制。
class CompactBinaryDataSocket extends DataSocket {
CompactBinaryDataSocket(Socket socket) throws IOException {
super(socket);
}
@Override
protected void writeInt(int i) throws IOException {
// uses one byte per 7 bit set.
long l = i & 0xFFFFFFFFL;
while (l >= 0x80) {
out.write((int) (l | 0x80));
l >>>= 7;
}
out.write((int) l);
}
@Override
protected void endOfBlock() throws IOException {
out.flush();
}
@Override
protected void nextBlock() {
// nothing
}
@Override
protected int readInt() throws IOException {
long l = 0;
int b, count = 0;
while ((b = in.read()) >= 0x80) {
l |= (b & 0x7f) << 7 * count++;
}
if (b < 0) throw new EOFException();
l |= b << 7 * count;
return (int) l;
}
}
文本,并在最后一个新行编码。
class TextDataSocket extends DataSocket {
TextDataSocket(Socket socket) throws IOException {
super(socket);
}
private boolean outBlock = false;
@Override
protected void writeInt(int i) throws IOException {
if (outBlock) out.write(' ');
out.write(Integer.toString(i).getBytes());
outBlock = true;
}
@Override
protected void endOfBlock() throws IOException {
out.write('\n');
out.flush();
outBlock = false;
}
private Scanner inLine = null;
@Override
protected void nextBlock() throws IOException {
inLine = new Scanner(in.readLine());
}
@Override
protected int readInt() throws IOException {
return inLine.nextInt();
}
}
Answer 6:
如果你想要一个以上的随机值发送到插座,选择一个简单的格式,使双方都同意它(发件人和reciever),例如,你可以简单地选择一个分隔符像;
并创建所有值的字符串与分隔然后发送
Answer 7:
的Android套接字服务器实施例修改为接收整数而不是字符串的数组:
...
class CommunicationThread implements Runnable {
private ObjectInputStream input;
public CommunicationThread(Socket clientSocket) {
try {
this.input = new ObjectInputStream(clientSocket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
int[] myMessageArray = (int[]) input.readObject();
String read = null;
read = String.format("%05X", myMessageArray[0] & 0x0FFFFF);
int i = 1;
do {
read = read + ", " + String.format("%05X", myMessageArray[i] & 0x0FFFFF);
i++;
} while (i < myMessageArray.length);
read = read + " (" + myMessageArray.length + " bytes)";
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
...
文章来源: how to write array to outputStream in Java