最近一个项目要C#做服务器给android发送图片和文本,但是android端接收图片老是出现问题!
C#端发送图片
public Byte[] getphoto(string photopath)
{
string str = photopath;
FileStream file = new FileStream(str, FileMode.Open, FileAccess.Read);
Byte[] bytBLOBData = new Byte[file.Length];
file.Read(bytBLOBData, 0, bytBLOBData.Length);
file.Close();
return bytBLOBData;
}
private void SendData(string data)
{
try
{
Byte[] msg = getphoto(data);
userList[0].socket.Send(msg, msg.Length, SocketFlags.None);
MessageBox.Show("" + msg.Length);
data = string.Format("To[{0}]:{1}", userList[0].socket.RemoteEndPoint.ToString(), data);
listBoxStatu.Invoke(AppendString, data);
}
catch
{
}
}
Android端接收线程:
private class ReceiveThread extends Thread {
private BufferedInputStream dis = null;
private Socket s = null;
ReceiveThread(Socket socket) {
try {
s = socket;
dis = new BufferedInputStream(s.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
while (isConnect) {
try {
Thread.sleep(1000);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[ 1024];
int len = -1;
while ((len = dis.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.flush();
outStream.close();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = 10; // width,hight设为原来的十分一
if (data.length > 0) {
bm = BitmapFactory.decodeByteArray(data, 0,
data.length, options);
if (bm != null) {
System.out.println(data.length);
myHandler.sendEmptyMessage(0);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
close();
}
}
}
}现在的问题是每次发送图片之后android端会一直堵塞卡在len = dis.read(buffer),并不会返回-1,只有在关闭服务器之后才会返回-1并显示图片,这个显然是不行的,求各位帮帮忙看看到底是哪里的问题!
------解决方案--------------------
第一个确保网络连接成功了。在dos下面telnet一下服务器。
然后 len = dis.read(buffer) 这地方是阻塞了。不知道你后台有没有异常。
然后看看这个。
?userList[0].socket.Send(msg,?msg.Length,?SocketFlags.None); 不知道你的服务器socket是怎么处理的。
------解决方案--------------------
在C#端发送完数据包以后,试试关闭连接
------解决方案--------------------
弄一个handler然后sendmessage.