问题描述
|
我已经阅读了很多有关Java套接字编程的问题/答复,但是没有一个问题适用于我当前的问题。
我已经编写了一个基本的Java ssl套接字程序,目前它的唯一目的是在客户端和服务器之间建立ssl连接,并由客户端发送一条签名消息。如果消息已由服务器验证,则应该相应地以(true!)或以(false!)进行答复。
当客户端向服务器发送一个“消息”并等待服务器响应时,握手后我陷入了困境。同时,服务器不会处理客户端发送的消息,因此它无法响应,我在那里等待他们中的任何一个继续处理。
你能告诉我我哪里做错了吗?
为了不显示大量不相关的代码,我没有包含值对象SignedMessage或Utils类。 utils类使用的方法用于序列化和反序列化,以及将String转换为字节数组。我知道我可以使用String.getBytes(),但是我喜欢手工完成转换。所有提到的方法都已经过测试并且工作正常。
ServerThread运行方法代码
public void run() {
try {
InputStream in = sslSocket.getInputStream();
OutputStream out = sslSocket.getoutputStream();
//if I write some output here the program works well,but this is not what I want to do
//out.write(\'!\');
//BASE64 DECODING
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int ch;
while((ch = in.read()) != -1)
bos.write(ch);
ByteArrayOutputStream decoded = new ByteArrayOutputStream();
Base64Encoder encoder = new Base64Encoder();
encoder.decode(bos.toByteArray(),bos.toByteArray().length,decoded);
//reconstructing the the SignedMessage object
SignedMessage signedMessage = (SignedMessage) Utils.deserializeObject(decoded.toByteArray());
if(checkSignature(signedMessage.getMessage().getBytes(\"UTF-8\"),signedMessage.getSignature(),signedMessage.getCertificate())){
System.out.println(String.valueOf(signedMessage.getMessage()));
//this i where I would like to write out the answer,but the code never get executed
out.write(Utils.toByteArray(\"TRUE!\"));
out.flush();
}
else {
out.write(Utils.toByteArray(\"false!\"));
}
} catch (IOException e) {
e.printstacktrace();
} finally {
try {
sslSocket.close();
} catch (IOException ex) {
ex.printstacktrace();
}
}
System.out.println(\"Thread closed\");
}
这是进行通信的客户代码
static void doProtocol(SSLSocket sslSocket) throws IOException,UnrecoverableKeyException,KeyStoreException,NoSuchAlgorithmException {
OutputStream out = sslSocket.getoutputStream();
InputStream in = sslSocket.getInputStream();
byte[] signature = generateSignature(Utils.toByteArray(Message),(PrivateKey) clientStore.getKey(Utils.CLIENT_NAME,Utils.CLIENT_PASSWORD),clientStore.getCertificate(Utils.CLIENT_NAME).getPublicKey().getAlgorithm());
//BASE64 ENCODING
byte[] object = Utils.serializeObject(new SignedMessage(Message,signature,clientStore.getCertificate(Utils.CLIENT_NAME)));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Base64Encoder encoder = new Base64Encoder();
encoder.encode(object,object.length,bos);
out.write(bos.toByteArray());
out.flush();
int ch;
while((ch = in.read()) != \'!\')
bos.write(ch);
System.out.println(\"Sesion closed\");
}
解决方法
这个
while((ch = in.read()) != -1)
bos.write(ch);
永远阻止。当流(连接)关闭时,这实际上将解除阻塞。
因此,由您来确定消息的结尾。
我的意思是消息的结束并不意味着流的结束。因此,收到消息后,您将无限期地等待渠道中的其他内容。
就像您在这里所做的一样
while((ch = in.read()) != \'!\')
bos.write(ch);