我正在尝试使用套接字通信制作一个简单的聊天应用程序。我的目标是成功发送和接收文本和图像(来自智能手机图库)。文本部分成功,但我在处理图像时遇到了问题。
我使用 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 循环是等待来自服务器的输入字节数组。处理程序在显示器上显示解码的字节数组。
--> img_input.readFully(byte_input); 我认为这条线有问题。我检查了该处理程序运行良好,并且在空的 while 块中,App 没有死。
会有什么问题?
服务器端代码如下图(消息线程省略)
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){}
}
}
}