我已经阅读了很多关于java套接字编程的问题/回复,但没有一个适用于我当前的问题。
我已经写了一个基本的java ssl套接字程序,它的唯一目的(目前)是在客户端和服务器之间建立一个ssl连接,并由客户端发送一条签名消息。如果消息得到服务器的验证,它应该相应地回复(true!)或者使用(false!)。
当客户端向服务器发送一条“消息”并等待服务器响应时,我在握手阶段之后被卡住了。同时,服务器不会处理客户端发送的消息,所以它不能响应,所以我正在等待它们中的任何一个继续处理。
你能告诉我我哪里弄错了吗?
为了不显示大量不相关的代码,我没有包括值对象SignedMessage或Utils类。utils类中使用的方法用于序列化和反序列化,以及将字符串转换为字节数组。我知道我可以使用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(), 0, 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, 0, object.length, bos);
out.write(bos.toByteArray());
out.flush();
int ch;
while((ch = in.read()) != '!')
bos.write(ch);
System.out.println("Sesion closed");
}发布于 2011-05-26 21:06:10
这
while((ch = in.read()) != -1)
bos.write(ch);永远阻塞。这实际上会在流(连接)关闭时解除阻塞。所以这取决于你来确定消息的结尾。我的意思是消息的结束并不意味着流的结束。因此,在您收到消息后,您将无限等待来自通道的其他smth。就像你在这里实际做的那样
while((ch = in.read()) != '!')
bos.write(ch);https://stackoverflow.com/questions/6138744
复制相似问题