安卓:通过套接字文件传输 [英] android: file transfer through sockets
问题描述
您好我试图通过套接字在Android信使发送文件。出于某种原因,它不工作。有时它的输出文件,但没有传输的字节是输出文件的0字节,有时输出或接收的文件是57字节precisely。继code其中其实我发送的文件:
公共布尔SENDFILE(字符串IP,端口INT){
尝试{
的String []海峡= ip.split(\\\\);
字节[] IP =新的字节[str.length]
的for(int i = 0; I< str.length;我++){
IP [i] =(字节)的Integer.parseInt(STR [I]);
}
Socket套接字= getSocket(InetAddress.getByAddress(IP),端口);
如果(插座== NULL){
返回false;
}
Log.i(SocketOP,SENDFILE-1);
文件f =新的文件(/ SD卡/聊天/ gas.jpg /);
文件大小=(INT)f.length(); 的BufferedOutputStream出=新的BufferedOutputStream(socket.getOutputStream()); 的FileInputStream FILEIN =新的FileInputStream(F);
Log.i(SocketOP,SENDFILE-2);
字节[]缓冲区=新的字节[文件大小]
INT读取动作= 0;
而((读取动作= fileIn.read(缓冲液))大于0){
out.write(缓冲液,0,读取动作);
}
了out.flush();
out.close();
fileIn.close();
Log.i(SocketOP,SENDFILE-3);
}赶上(IOException异常五){
返回false;
//e.printStackTrace();
}
返回true;
}
这是我的的InputStream发送到receivefile方法:
私有类ReceiveConnection继承Thread { 插座ClientSocket的= NULL;
公共ReceiveConnection(Socket套接字){
this.clientSocket =插座;
SocketOperator.this.sockets.put(socket.getInetAddress(),插座);
} @覆盖
公共无效的run(){
尝试{
//为PrintWriter了=的新PrintWriter(clientSocket.getOutputStream(),TRUE);
在的BufferedReader =新的BufferedReader(新的InputStreamReader(
clientSocket.getInputStream()));
串inputLine; 而((inputLine = in.readLine())!= NULL){
InputStream为= clientSocket.getInputStream();
如果(inputLine.contains(文本)==真){
appManager.messageReceived(inputLine);
Log.i(SocketOP,文字); }否则如果(inputLine.contains(文本)== FALSE){
Log.i(SocketOP,filee);
appManager.fileReceived(是);
}其他{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
Log.i(SocketOP,关闭连接);
}
}
}
}
}
和最后这是我收到的文件:
公共无效fileReceived(InputStream为)
抛出FileNotFoundException异常,IOException异常{
Log.i(IMSERVICE,FILERECCC-1); // INT文件大小= 6022386; //文件大小暂难codeD INT读取动作; 最后一个字节[] = aByte新的字节[is.toString()长()];
如果(是!= NULL){
ByteArrayOutputStream BAOS =新ByteArrayOutputStream();
FOS的FileOutputStream = NULL;
BOS的BufferedOutputStream = NULL;
尝试{
FOS =新的FileOutputStream(/ SD卡/聊天/ gas1.jpg /);
BOS =新的BufferedOutputStream(FOS);
读取动作= is.read(aByte,0,aByte.length); 做{
baos.write(aByte);
读取动作= is.read(aByte);
}而(读取动作!= -1); bos.write(baos.toByteArray());
bos.flush();
bos.close();
Log.i(IMSERVICE,FILERECCC-2); }赶上(IOException异常前){
//做异常处理
}
}
}}
以下是完整socketoperator文件:
包hardy.scl.communication;进口hardy.scl.interfaces.IAppManager;
进口hardy.scl.interfaces.ISocketOperator;进口java.io.BufferedInputStream中;
进口java.io.BufferedOutputStream;
进口java.io.BufferedReader中;
进口的java.io.File;
进口java.io.FileInputStream中;
进口java.io.FileNotFoundException;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.OutputStream中;
进口java.io.OutputStreamWriter中;
进口的java.io.PrintWriter;
进口java.net.HttpURLConnection中;
进口java.net.InetAddress中;
进口java.net.MalformedURLException;
进口java.net.ServerSocket的;
进口的java.net.Socket;
进口的java.net.URL;
进口的java.net.UnknownHostException;
进口的java.util.HashMap;
进口java.util.Iterator的;进口android.util.Log;
公共类SocketOperator实现ISocketOperator
{
私有静态最后弦乐AUTHENTICATION_SERVER_ADDRESS =http://10.10.10.100/chippers/;私人INT listeningPort = 0;私有静态最后弦乐HTTP_REQUEST_FAILED = NULL;私人的HashMap< InetAddress类,插座>插座=新的HashMap< InetAddress类,插座>();私人的ServerSocket ServerSocket的= NULL;私人布尔聆听;私人IAppManager AppManager的;公众诠释文件大小;私有类ReceiveConnection继承Thread {
插座ClientSocket的= NULL;
插座fileSocket = NULL;
公共ReceiveConnection(Socket套接字)
{
this.clientSocket =插座;
this.fileSocket =插座;
SocketOperator.this.sockets.put(socket.getInetAddress(),插座);
}@覆盖
公共无效的run(){
尝试{
//为PrintWriter了=的新PrintWriter(clientSocket.getOutputStream(),TRUE);
在的BufferedReader =新的BufferedReader(
新的InputStreamReader(
clientSocket.getInputStream())); InputStream为= fileSocket.getInputStream(); 串inputLine;
而((inputLine = in.readLine())!= NULL){ 如果(inputLine.contains(文本)==真)
{
appManager.messageReceived(inputLine);
Log.i(SocketOP,文字);} 否则,如果
(inputLine.contains(文本)== FALSE)
{ Log.i(SocketOP,filee);
appManager.fileReceived(是); }
其他{ clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close(); fileSocket.shutdownInput();
fileSocket.shutdownOutput();
fileSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
SocketOperator.this.sockets.remove(fileSocket.getInetAddress()); Log.i(SocketOP,关闭连接);
}
} }赶上(IOException异常五){
Log.e(ReceiveConnection.run:接收连接时,);
}
}
}公共SocketOperator(IAppManager的AppManager){
this.appManager = AppManager的;
}
公共字符串sendHtt prequest(字符串PARAMS)
{
URL网址;
字符串结果=新的String();
尝试
{
URL =新的URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection的连接;
连接=(HttpURLConnection类)url.openConnection();
connection.setDoOutput(真); 为PrintWriter了=的新PrintWriter(connection.getOutputStream()); 通过out.println(PARAMS);
out.close(); 在的BufferedReader =新的BufferedReader(
新的InputStreamReader(
connection.getInputStream()));
串inputLine; 而((inputLine = in.readLine())!= NULL){
结果= result.concat(inputLine);
}
附寄();
}
赶上(MalformedURLException的E){
e.printStackTrace();
}
赶上(IOException异常五){
e.printStackTrace();
}如果(result.length()== 0){
结果= HTTP_REQUEST_FAILED;
}返回结果;
}
公共布尔的sendMessage(字符串消息,串IP,端口INT)
{
尝试{
的String []海峡= ip.split(\\\\); 字节[] IP =新的字节[str.length] 的for(int i = 0; I< str.length;我++){ IP [i] =(字节)的Integer.parseInt(STR [I]);
}
Socket套接字= getSocket(InetAddress.getByAddress(IP),端口);
如果(插座== NULL){
返回false;
} PrintWriter的出= NULL;
OUT =的新PrintWriter(socket.getOutputStream(),TRUE);
// OutputStreamWriter的OutputStream =新OutputStreamWriter(socket.getOutputStream());
//outputStream.write(\"Text);
// outputStream.flush();
串旗=文本;
消息=消息+标志;
通过out.println(消息);
}赶上(UnknownHostException异常五){
返回false;
//e.printStackTrace();
}赶上(IOException异常五){
返回false;
//e.printStackTrace();
}返回true;
}
公众诠释startListening(INT PORTNO)
{
听= TRUE;尝试{
ServerSocket的=新的ServerSocket(PORTNO);
this.listeningPort = PORTNO;
}赶上(IOException异常五){ //e.printStackTrace();
this.listeningPort = 0;
返回0;
}而(听){
尝试{
新ReceiveConnection(的ServerSocket.accept())开始()。 }赶上(IOException异常五){
//e.printStackTrace();
返回2;
}
}尝试{
serverSocket.close();
}赶上(IOException异常五){
Log.e(异常服务器套接字,异常关闭服务器socket时);
返回3;
}
返回1;
}
公共无效的stopListening()
{
this.listening = FALSE;
}私人插座getSocket(InetAddress类地址,诠释PORTNO)
{
Socket套接字= NULL;
如果(sockets.containsKey(地址)==真)
{
插座= sockets.get(地址);
//检查套接字的状态
如果(socket.isConnected()== ||假
socket.isInputShutdown()==真||
socket.isOutputShutdown()==真||
socket.getPort()!= PORTNO
)
{
//如果插座不适合,然后创建一个新的套接字
sockets.remove(地址);
尝试{
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
插座=新的Socket(地址,PORTNO);
sockets.put(地址,插座);
}
赶上(IOException异常五){
Log.e(getSocket:关闭并移除时,);
}
}
}
其他
{
尝试{
插座=新的Socket(地址,PORTNO);
sockets.put(地址,插座);
}赶上(IOException异常五){
Log.e(getSocket:在创建的时候,);
}
}
返回插座;
}
公共无效的exit()
{
为(迭代&所述;插座方式>迭代= sockets.values()迭代(); iterator.hasNext())
{
Socket套接字=(插座)iterator.next();
尝试{
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
}赶上(IOException异常E)
{
}
}sockets.clear();
this.stopListening();
AppManager的= NULL;
// timer.cancel();
}
公众诠释getListeningPort(){返回this.listeningPort;
}
@覆盖
公共布尔SENDFILE(字符串IP,端口INT){
// TODO自动生成方法存根
尝试{
的String []海峡= ip.split(\\\\); 字节[] IP =新的字节[str.length] 的for(int i = 0; I< str.length;我++){ IP [i] =(字节)的Integer.parseInt(STR [I]);
}
Socket套接字= getSocket(InetAddress.getByAddress(IP),端口);
如果(插座== NULL){
返回false;
}
Log.i(SocketOP,SENDFILE-1);
文件f =新的文件(/ SD卡/聊天/ gas.jpg /); 二BufferedInputStream为=新的BufferedInputStream(新的FileInputStream(F));
INT READDATA;
字节[]缓冲区=新的字节[1024];
bis.read(缓冲液,0,buffer.length);
OutputStream的OS = socket.getOutputStream(); 而(!(READDATA = bis.read(缓冲液))= - 1){
os.write(缓冲液,0,READDATA);
Log.i(SocketOP,SENDFILE-3);
}}赶上(IOException异常五){
返回false;
//e.printStackTrace();
}
// Toast.makeText(这一点,Lvbvhhging ...,Toast.LENGTH_SHORT).show();返回true;
}
}
这是一个运行,并呼吁startlistening我IMService服务。我完全cluless。它给我一个错误的怀疑。我怎么去解决,现在这个..
IMService code座:
公共无效的onCreate()
{
MNM =(NotificationManager)getSystemService(NOTIFICATION_SERVICE); //显示关于我们开始通知。我们把在状态栏中的图标。
// showNotification();
conManager =(ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
//定时器用来把好友列表信息,每隔UPDATE_TIME_PERIOD;
定时器=新定时器(); 线程线程=新主题()
{
@覆盖
公共无效的run(){ //socketOperator.startListening(LISTENING_PORT_NO);
随机随机=新的随机();
INT tryCount = 0;
而(socketOperator.startListening(10000 + random.nextInt(20000))== 0)
{
tryCount ++;
如果(tryCount→10)
{
//如果不能听尝试10次后的端口,放弃...
打破;
} }
}
};
thread.start();}
看看这个fileReceived
公共无效fileReceived(InputStream为)
抛出FileNotFoundException异常,IOException异常{
Log.i(IMSERVICE,FILERECCC-1);
如果(是!= NULL){
FOS的FileOutputStream = NULL;
BOS的BufferedOutputStream = NULL;
尝试{
FOS =新的FileOutputStream(/ SD卡/聊天/ gas1.jpg /);
BOS =新的BufferedOutputStream(FOS);
字节[] = aByte新的字节[1024];
INT读取动作; 而((读取动作= is.read(aByte))!= -1){
bos.write(aByte,0,读取动作);
}
bos.flush();
bos.close();
Log.i(IMSERVICE,FILERECCC-2); }赶上(IOException异常前){
//做异常处理
}
}
}}
修改
您可以使用2个插槽,不同端口上侦听。例如。
MESSAGE_PORT = 20000
FILE_PORT = 20001
和运行2 ReceiveConnection
S,例如 ReceiveFileConnection
和 ReceiveMessageConnection
。我不知道你是否启动端口监听,它在你的code不是上面的地方。
在客户端,您还需要拆分发送给2部分,邮件发件人发送到MESSAGE_PORT和文件将文件发送到FILE_PORT。
EDIT2
- 我分裂
ReceiveConnection
成2类ReceiveMessageConnection
和ReceiveFileConnection
。 -
我修改方法
startListening
,因此它需要我们要启动的消息或文件,listener参数。所以,你需要两次调用它像startListening(MESSAGE_PORT,真实);
startListening(FILE_PORT,FALSE);
不过,打电话给他们在不同的线程。
要送你叫的sendMessage(信息,IP,MESSAGE_PORT)
和对文件的消息 SENDFILE(IP,FILE_PORT)
。
希望这会有所帮助。
hi i am trying to send a file through sockets in an android messenger. for some reason its not working. at times it does output a file but transfers no bytes that is the output file is of 0 bytes and sometimes the output or the received file is of 57 bytes precisely. following the code where i actually send the file :
public boolean sendFile(String ip, int port) {
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
Log.i("SocketOP", "sendFILE-1");
File f = new File("/sdcard/chats/gas.jpg/");
filesize = (int) f.length();
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
FileInputStream fileIn = new FileInputStream(f);
Log.i("SocketOP", "sendFILE-2");
byte [] buffer = new byte [filesize];
int bytesRead =0;
while ((bytesRead = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.flush();
out.close();
fileIn.close();
Log.i("SocketOP", "sendFILE-3");
} catch (IOException e) {
return false;
//e.printStackTrace();
}
return true;
}
this is where i send the inputstream to the receivefile method :
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket) {
this.clientSocket = socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
@Override
public void run() {
try {
//PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
InputStream is=clientSocket.getInputStream();
if (inputLine.contains("Text") == true) {
appManager.messageReceived(inputLine);
Log.i("SocketOP","text");
} else if (inputLine.contains("Text") == false) {
Log.i("SocketOP","filee");
appManager.fileReceived(is);
} else {
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
Log.i("SocketOP", "CLOSING CONNECTION");
}
}
}
}
}
and finally this is how i receive the file :
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Log.i("IMSERVICE", "FILERECCC-1");
//int filesize=6022386; // filesize temporary hardcoded
int bytesRead;
final byte[] aByte = new byte[is.toString().length()];
if (is!= null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("/sdcard/chats/gas1.jpg/");
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
Log.i("IMSERVICE", "FILERECCC-2");
} catch (IOException ex) {
// Do exception handling
}
}
}}
the following is the complete socketoperator file :
package hardy.scl.communication;
import hardy.scl.interfaces.IAppManager;
import hardy.scl.interfaces.ISocketOperator;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import android.util.Log;
public class SocketOperator implements ISocketOperator
{
private static final String AUTHENTICATION_SERVER_ADDRESS = "http://10.10.10.100/chippers/";
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private IAppManager appManager;
public int filesize ;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
Socket fileSocket=null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
this.fileSocket=socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
@Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
InputStream is=fileSocket.getInputStream();
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("Text") == true)
{
appManager.messageReceived(inputLine);
Log.i("SocketOP","text");}
else if
(inputLine.contains("Text") == false)
{
Log.i("SocketOP","filee");
appManager.fileReceived(is);
}
else{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
fileSocket.shutdownInput();
fileSocket.shutdownOutput();
fileSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
SocketOperator.this.sockets.remove(fileSocket.getInetAddress());
Log.i("SocketOP", "CLOSING CONNECTION");
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public SocketOperator(IAppManager appManager) {
this.appManager = appManager;
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
public boolean sendMessage(String message, String ip, int port)
{
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
PrintWriter out = null;
out = new PrintWriter(socket.getOutputStream(), true);
//OutputStreamWriter outputStream = new OutputStreamWriter(socket.getOutputStream());
//outputStream.write("Text");
// outputStream.flush();
String flag = "Text";
message = message+flag;
out.println(message);
} catch (UnknownHostException e) {
return false;
//e.printStackTrace();
} catch (IOException e) {
return false;
//e.printStackTrace();
}
return true;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
private Socket getSocket(InetAddress addr, int portNo)
{
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
try {
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
appManager = null;
// timer.cancel();
}
public int getListeningPort() {
return this.listeningPort;
}
@Override
public boolean sendFile(String ip, int port) {
// TODO Auto-generated method stub
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
Log.i("SocketOP", "sendFILE-1");
File f = new File("/sdcard/chats/gas.jpg/");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
int readData;
byte[] buffer = new byte[1024];
bis.read(buffer, 0,buffer.length);
OutputStream os = socket.getOutputStream();
while((readData=bis.read(buffer))!=-1){
os.write(buffer,0,readData);
Log.i("SocketOP", "sendFILE-3");
}
} catch (IOException e) {
return false;
//e.printStackTrace();
}
// Toast.makeText(this, "Lvbvhhging...", Toast.LENGTH_SHORT).show();
return true;
}
}
This is my IMService service that runs and calls startlistening. i am totally cluless. its giving me an error as suspected. how do i go about resolving this now.. IMService code block :
public void onCreate()
{
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar.
// showNotification();
conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
// Timer is used to take the friendList info every UPDATE_TIME_PERIOD;
timer = new Timer();
Thread thread = new Thread()
{
@Override
public void run() {
//socketOperator.startListening(LISTENING_PORT_NO);
Random random = new Random();
int tryCount = 0;
while (socketOperator.startListening(10000 + random.nextInt(20000)) == 0 )
{
tryCount++;
if (tryCount > 10)
{
// if it can't listen a port after trying 10 times, give up...
break;
}
}
}
};
thread.start();
}
Try this for fileReceived
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Log.i("IMSERVICE", "FILERECCC-1");
if (is!= null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("/sdcard/chats/gas1.jpg/");
bos = new BufferedOutputStream(fos);
byte[] aByte = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(aByte)) != -1) {
bos.write(aByte, 0, bytesRead);
}
bos.flush();
bos.close();
Log.i("IMSERVICE", "FILERECCC-2");
} catch (IOException ex) {
// Do exception handling
}
}
}}
EDIT
You can use 2 sockets, listening on different ports. E.g.
MESSAGE_PORT = 20000
FILE_PORT = 20001
And you run 2 ReceiveConnection
s, e.g. ReceiveFileConnection
and ReceiveMessageConnection
. I don't know where do you start port listening, it's not in your code above.
In client you'll also need to split sending to 2 part, message sender sends to MESSAGE_PORT and file sends files to FILE_PORT.
EDIT2
- I split
ReceiveConnection
into 2 classesReceiveMessageConnection
andReceiveFileConnection
. I modified method
startListening
, so it takes parameter which listener we want to start message or file. So you need to call it twice likestartListening(MESSAGE_PORT, true);
startListening(FILE_PORT, false);
But call them in different threads.
To send message you call sendMessage("Message", ip, MESSAGE_PORT)
and for files sendFile(ip, FILE_PORT)
.
Hope this will help.
这篇关于安卓:通过套接字文件传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!