我正在尝试修改我最初只能发送字符串的 android 代码。任务是让它可以传输图片。我知道有很多不同的方法可以实现这一点。但是我试过了,真的不知道为什么我的图片不能发送,虽然连接没有问题。有谁能告诉我吗?我会很感激的。我只是一个初学者,请忘记我糟糕的编程技能。
这是下面服务器的主要部分
private Runnable socket_server = new Runnable(){
public void run(){
handler.post(new Runnable() {
public void run() {
test.setText("Listening...." + getMyIp());
}
});
try{
serverSocket = new ServerSocket(1234);
while (true) {
Socket client = serverSocket.accept();
handler.post(new Runnable() {
public void run() {
test.setText("Connected.");
}
});
try {
File myFile = new File ("/sdcard/DCIM/img2.jpg");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = client.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
os.flush();
client.close();
test.setText("Received.");
} catch (Exception e) {
handler.post(new Runnable() {
public void run() {
test.setText("Sending erro");
}
});
}
}
}catch(IOException e){
handler.post(new Runnable() {
public void run() {
test.setText("Fail to buitl the socket");
}
});
}
}
};
这是客户的一部分
new Thread()
{
@Override
public void run() {
// TODO Auto-generated method stub
InetAddress serverAddr = null;
SocketAddress sc_add = null;
Socket socket = null;
try
{
serverAddr = InetAddress.getByName("192.168.1.105");
sc_add= new InetSocketAddress(serverAddr,1234);
socket = new Socket();
socket.connect(sc_add,2000);
File myFile = new File("/sdcard/DCIM/img2.jpg");
InputStream fis = new FileInputStream("/sdcard/DCIM/img2.jpg");
OutputStream outputStream = socket.getOutputStream();
byte [] buffer = new byte[(int)myFile.length()];
int temp = 0 ;
while((temp = fis.read(buffer)) != -1){
outputStream.write(buffer, 0, temp);
}
outputStream.flush();
socket.close();
} catch (UnknownHostException e) {
//TextView01.setText("InetAddress fail");
} catch (SocketException e) {
//TextView01.setText("fail to develop socket");
} catch(IOException e) {
//TextView01.setText("fail to sending");
}
}
}.start();