我一直致力于实现java SSL套接字程序,并且客户端接收(和输出)服务器发送的消息的顺序存在问题。我花了几个小时试图了解正在发生的事情,正如代码所做的那样 - 至少对我和其他看过它的人 - 逻辑意义。
到目前为止,我们发现客户端收到一个空字符串并打印到控制台。
这是我用来发送消息的方法:
public void returnCode(int returnCode) {
try {
System.out.println(id + "S :" + returnCode);
out.writeBytes(returnCode + "\n\r");
out.flush();
} catch (IOException e) {
System.out.println("Unable to return code to:" + id);
}
}
我在多个线程中运行它,这意味着为每个连接的客户端创建一个新的“连接线程”:
while (true) {
id++;
try {
System.out.println("Connection Received. Starting Thread " + id);
sslsocket = (SSLSocket)sslserversocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new threa for a client
new MDTPConnectionThread(sslsocket, id).start();
}
在服务器级别,它们共享相同的Socket。 id
仅用于跟踪线程。
这是发送代码的服务器逻辑:
try {
line = brinp.readLine();
System.out.println(id + "R :" + line);
if(line.contains(Integer.toString(SYN))){
returnCode(SYN_ACK);
} else {
returnCode(PERROR);
socket.close();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println(id + " : Handshake failed in Stage 2");
}
try {
line = brinp.readLine();
System.out.println(id + "R :" + line);
if(line.contains(Integer.toString(SYN_SUC))){
returnCode(AUTH);
} else {
returnCode(PERROR);
socket.close();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println(id + " : Handshake failed in Stage 3");
}
try {
line = brinp.readLine();
System.out.println(id + "R :" + line);
if(line.contains("auth_key")) {
returnCode(SUCCESS);
} else {
returnCode(PEM_DENIED);
System.out.println(id + " : PERMISSION DENIED");
socket.close();
};
} catch (IOException e1) {
System.out.println(id + " : Handshake failed in Stage 3");
}
这会在服务器上提供正确的输出:
1R :201
1S :202
1R :203
1S :100
1R :auth_key
1S :200
不幸的是客户端使用以下代码:
String string = null;
String returnString = null;
bufferedwriter.write("201" + '\n');
bufferedwriter.flush();
while (true) {
returnString = in.readLine();
System.out.println(returnString);
string = bufferedreader.readLine();
bufferedwriter.write(string + '\n');
bufferedwriter.flush();
try {
Thread.sleep(2000);
} catch (InterruptedException e){
e.printStackTrace();
}
}
将此作为输出:
201 (s)
202
203 (s)
auth_key (s)
100
标有(s)的是客户发送的。我已经尝试添加延迟以等待消息返回,但这没有任何帮助。我正在本地主机上试验这个,所以网络中的真正延迟不应成为问题。 知道问题可能是什么?特别是考虑到它在一开始就有效。
谢谢, Jsincn