ソケット通信を使った簡単なチャットアプリを作ろうとしています。私の目標は、テキストと画像 (スマートフォン ギャラリーから) を正常に送受信することです。テキスト部分は成功しましたが、画像に問題があります。
dataInput/OutputStream を使用してコードを作成しました。以下は、bytearray を使用して画像転送用のソケット接続を確立するコードです (アプリはテキストと画像に異なるポートを使用します)。
class image_connection_thread extends Thread{
public boolean flag=true;
public void run(){
try{
socket2 = new Socket(Ip,port_img);
//Imgage Streams
img_output= new DataOutputStream(socket2.getOutputStream());
img_input= new DataInputStream(socket2.getInputStream());
while(flag)
{
///////////////////
img_input.readFully(byte_input);
**////// This line makes problem(App dies). But no exception message occurs. ////**
if(byte_input==null)
break;
image_received=BitmapFactory.decodeByteArray(byte_input, 0, byte_input.length);
Message Msg = new Message();
Msg.obj=image_received;
handler_img.sendMessage(Msg);
}
socket2.close();
}catch(Exception e)
{
tv_Text.append(e.getMessage()+"connection failed3\n");
}
}
}
while ループは、サーバーからの入力 bytearray を待機することです。ハンドラーは、デコードされた bytearray をディスプレイに表示します。
--> img_input.readFully(byte_input); この行が問題になると思います。ハンドラーが正常に動作することを確認しました。空の while ブロックを使用しても、アプリは停止しませんでした。
問題は何でしょうか?
サーバー側のコードを以下に示します。 (メッセージスレッドは省略)
public class server
{
public static void main(String[] args) {
Thread thread1=new port1_thread();
Thread thread2=new port2_thread();
thread1.start();
thread2.start();
}
}
class port2_thread extends Thread
{
ServerSocket serversocket = null;
public void run()
{
try
{
serversocket = new ServerSocket(9003);
while(true)
{
Socket socket = serversocket.accept();
Thread thread= new image_thread(socket);
thread.start();
}
}catch(Exception e){System.out.println("1-2"+e.getMessage());}
}
}
class image_thread extends Thread
{
static ArrayList<DataOutputStream> list2 = new ArrayList<DataOutputStream>();
Socket socket;
DataOutputStream output2 = null;
image_thread(Socket socket)//constructor
{
this.socket=socket;
try //data output stream
{
output2 = new DataOutputStream(socket.getOutputStream());
list2.add(output2);
}
catch (Exception e)
{
System.out.println("22"+e.getMessage());
}
}
public void run()
{
try
{
//output2= new DataOutputStream(socket.getOutputStream());
DataInputStream input2=new DataInputStream(socket.getInputStream());
while(true)
{
for (DataOutputStream output2 : list2)
{
byte[] b = new byte[1024];
input2.readFully(b);
output2.write(b);
output2.flush();
}
}
}catch(Exception e){System.out.println("33"+e.getMessage());}
finally
{
list2.remove(output2);
try
{
socket.close();
}catch(Exception ignored){}
}
}
}