Python Imaging Library を使用して画像を描画するサーバー側関数があります。Java クライアントはイメージを要求します。イメージはソケットを介して返され、BufferedImage に変換されます。
送信する画像のサイズをデータの前に付け、その後に CR を付けます。次に、ソケット入力ストリームからこのバイト数を読み取り、ImageIO を使用して BufferedImage に変換しようとします。
クライアントの短縮コード:
public String writeAndReadSocket(String request) {
// Write text to the socket
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bufferedWriter.write(request);
bufferedWriter.flush();
// Read text from the socket
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Read the prefixed size
int size = Integer.parseInt(bufferedReader.readLine());
// Get that many bytes from the stream
char[] buf = new char[size];
bufferedReader.read(buf, 0, size);
return new String(buf);
}
public BufferedImage stringToBufferedImage(String imageBytes) {
return ImageIO.read(new ByteArrayInputStream(s.getBytes()));
}
そしてサーバー:
# Twisted server code here
# The analog of the following method is called with the proper client
# request and the result is written to the socket.
def worker_thread():
img = draw_function()
buf = StringIO.StringIO()
img.save(buf, format="PNG")
img_string = buf.getvalue()
return "%i\r%s" % (sys.getsizeof(img_string), img_string)
これは文字列の送受信には機能しますが、画像変換は (通常) 失敗します。画像が正しく読み取られない理由を理解しようとしています。私の最善の推測は、クライアントが適切なバイト数を読み取っていないということですが、正直なところ、なぜそうなるのかはわかりません。
補足:
- char[]-to-String-to-bytes-to-BufferedImage Java ロジックは回り道ですが、バイトストリームを直接読み取ると同じエラーが発生します。
- クライアントソケットが永続的ではない、つまり. 要求が処理され、接続が切断されます。画像サイズを気にする必要がないため、そのバージョンは問題なく動作しますが、提案されたアプローチが機能しない理由を知りたいです。