我試圖修改我最初只能發送字符串的android代碼。任務是讓它可以傳輸圖片。我知道有很多不同的方法來實現這一點。但我試過,真的不知道爲什麼我的照片無法發送,雖然連接沒有問題。 有誰能告訴我?我會很感激它。 我只是一個初學者,請忘記我可憐的編程技巧。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();
真的謝謝你的明確答案。但我試過你顯示的方式,似乎仍然有一些問題與我的程序... –
更新您的問題與更多的信息 –