【发布时间】:2013-02-02 15:22:54
【问题描述】:
我们有一个 java 套接字程序,服务器从许多设备获取数据并且工作正常。有时服务器需要向设备发送一些命令。当它发送单个命令时,它工作正常。当它发送多个命令时,问题就来了,只有第一个是成功的。我们无法弄清楚为什么其余的都失败了。下面是显示消息如何发送的 sn-p。我应该在消息发送后设置延迟吗?
public static void main(String[] args) {
new sServer7888();
}
sServer7888() {
try{
final ServerSocket serverSocketConn = new ServerSocket(7888);
while (true){
try{
Socket socketConn1 = serverSocketConn.accept();
new Thread(new ConnectionHandler(socketConn1)).start();
}
catch(Exception e){
e.printStackTrace(System.out);
}
}
}
catch (Exception e) {
e.printStackTrace(System.out);
}
}
class ConnectionHandler implements Runnable {
private Socket receivedSocketConn1;
ConnectionHandler(Socket receivedSocketConn1) {
this.receivedSocketConn1=receivedSocketConn1;
}
public void run() {
while ((nextChar=readIn1.read()) != -1) {
completeMessage += (char) nextChar;
if (nextChar == '*')
{
String[] splitResult = completeMessage .split(",");
String header=splitResult[0].trim().substring(0,4);
if((header.equals("$ACK")){
//update the message sent from the server as already acknowledge.
}
else{
//run query to find if there are any message to be sent out to the devices
while(rsOC1.next()){
commandText = rsOC1.getString("commandText");
writeOut1.write(commandText);
writeOut1.write("\r\n");
writeOut1.flush();
}
//now process the normal message receive from the devices.
}
completeMessage="";
}
}
}
}
【问题讨论】:
-
您是否检查过
rs0c1.next()在第一次迭代后是否返回true? -
@VishalK 是的,我已经检查过它是否工作正常,因为我收到了很多这样的消息。
-
如果把客户端接收消息的代码放在这里就好了...
-
您是否尝试过查看 writeOut1.flush() 的行为?
-
@Prateek :我认为在每次写入会话后清除 OutputStream 是一个好习惯。