【发布时间】:2014-07-04 09:01:37
【问题描述】:
我需要通过 Java 套接字向服务器发送一条文本消息,然后发送一个字节数组,然后发送一个字符串等... 到目前为止我开发的东西正在工作,但客户端设法只读取已发送的第一个字符串。
从服务器端:我使用BufferedOutputStream 发送字节数组,并使用PrintWriter 发送字符串。
问题是客户端和服务器不同步,我的意思是服务器发送字符串然后字节数组然后字符串而不等待客户端消耗每个需要的字节。
我的意思是场景不是这样的:
Server Client
Send String read String
Send byte read byte
但它是这样的:
Server Client
Send String
Send byte
Send String
Send byte
read String
read byte
read String
read byte
可能有用的是我确切知道每个字符串的大小和要读取的每个字节数组。
下面是分别用于发送字符串和字节数组的方法:
// Send String to Client
// --------------------------------------------------------------------
public void sendStringToClient (
String response,
PrintWriter output) {
try {
output.print(response);
output.flush();
} catch(Exception e) {
e.printStackTrace();
}
System.out.println("send Seeder String : " + response);
}
// Send Byte to Client
// --------------------------------------------------------------------
public void sendByteToClient (
byte[] response,
BufferedOutputStream output) {
try {
output.write(response, 0, response.length);
//System.out.println("send : " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
下面是分别用于读取字符串和字节数组的方法:
public byte[] readInByte(int size) {
byte[] command = new byte[size];
try {
this.inByte.read(command);
} catch (IOException e) {
e.printStackTrace();
}
return command;
}
public String readInString(int size) {
char[] c = new char[size];
try{
this.inString.read(c, 0, size);
} catch (IOException e) {
e.printStackTrace();
}
return String.valueOf(c);
}
【问题讨论】:
-
我们可以看到您用于实现此目的的客户端和服务器代码吗?
-
@publ1c_stat1c 看看上面的代码。thks
-
@mitchellZ,...我有和你一样的情况。那么你现在怎么解决呢?
-
@gumuruh 我所做的是使用字符串数据和字节数据之间的分隔符将所有内容作为字节数组发送,在客户端我逐字节读取,每当我找到分隔符时我就会知道如果我必须以字符串或字节的形式读取缓冲区上的数据...顺便说一句,我尝试使用可序列化对象通过同一个套接字发送字符串和字节数组,但这非常慢(您可能已经知道)。祝你好运!