Am developing one android application which requires print option. I used the following code to do this in wifi printer, but it giving Networkonmainthread exception
try {
Socket sock = new Socket("192.168.199.245", 9100); // ip and port of printer
PrintWriter oStream = new PrintWriter(sock.getOutputStream());
oStream.println("\t\t Text to The Printer");
oStream.println("\n\n\n");
oStream.close();
sock.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Has anyone know how do this? i need a sample code for print in wifi printer.....thanks
My code is working:
WifiPrint.java
public class WifiPrint extends Activity { TextView printer_name,
gate_way, printer_port; int port = 9100; WifiManager wifi = null;
android.net.DhcpInfo d; String gateway_ip = "";
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_print); wifi = (WifiManager)
getSystemService(Context.WIFI_SERVICE); printer_name = (TextView)
findViewById(R.id.textView1); gate_way = (TextView)
findViewById(R.id.textView2); printer_port = (TextView)
findViewById(R.id.textView3);
/* de.lohndirekt.print.IppPrintService svc = new IppPrintService(printerURI); InputStream stream = new
BufferedInputStream(new FileInputStream("image.epl")); DocFlavor
flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; Doc myDoc = new
SimpleDoc(stream, flavor, null); DocPrintJob job =
svc.createPrintJob(); job.print(myDoc, null);*/
}
#Override public boolean onCreateOptionsMenu(Menu menu) { //
Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.wifi_print, menu); return true;
}
public void wifisettings(View v) { startActivityForResult(new
Intent(
android.provider.Settings.ACTION_WIFI_SETTINGS), 0); }
public void connectSocket(View v) {
/*Uri filepath=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.pdfsample); Toast.makeText(this, filepath.getPath(), Toast.LENGTH_LONG).show(); */ ClientThread clientThread = new
ClientThread(""); Thread clientstartThread = new
Thread(clientThread); clientstartThread.start(); }
public String intToIp(int i) { return ((i & 0xFF) + "." + ((i >> 8)
& 0xFF) + "." + ((i >> 16) & 0xFF)
+ "." + ((i >> 24) & 0xFF)); }
#Override protected void onActivityResult(int requestCode, int
resultCode, Intent data) { // TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data); if
(requestCode == 0) { WifiInfo wifiinfo = wifi.getConnectionInfo();
d = wifi.getDhcpInfo();
printer_name.setText("Name:" + wifiinfo.getSSID()); gateway_ip =
intToIp(d.gateway); gate_way.setText("Printer Ip:" + gateway_ip);
printer_port.setText("Port:" + port);
} }
public File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File("/sdcard/testpdf.pdf");
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null; }
class ClientThread implements Runnable { String filepath = "";
BufferedInputStream bis = null; FileInputStream fis;
Socket socket;
public ClientThread(String filename) { filepath = filename; }
#Override public void run() { // TODO Auto-generated method
stub try {
InputStream in = getResources().openRawResource(R.raw.pdfsample);
createFileFromInputStream(in);
File pdfFile = new File("/sdcard/testpdf.pdf");
byte[] mybytearray = new byte[(int) pdfFile.length()];
socket = new Socket(gateway_ip, port);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(socket.isConnected()){
Toast.makeText(WifiPrint.this,
"Socket Connected",
Toast.LENGTH_LONG).show();
}
}
});
fis = new FileInputStream(pdfFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = socket.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
if (bis != null) {
bis.close();
os.close();
socket.close();
fis.close();
}
} catch (final UnknownHostException e) {
// TODO Auto-generated catch block
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(WifiPrint.this,
"UnHost Exceptions" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}); } catch (final IOException e) {
// TODO Auto-generated catch block
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(WifiPrint.this,
"Io Exceptions" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}); } finally {
try {
if (bis != null) {
bis.close();
socket.close();
fis.close();
}
} catch (final IOException e) {
// TODO Auto-generated catch block
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(
WifiPrint.this,
"Io Exeption in Closing Socket"
+ e.getMessage(), Toast.LENGTH_LONG)
.show();
}
});
} } }
}
}
And Add certain permssions in manifest file:
<uses-feature android:name="android.hardware.wifi" />
Just paste this code in your main activity..
StrictMode.setThreadPolicy(new Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
Related
I'm developing a project where client sends screenshots of its activity to server where the bitmap is converted to string.For me it works well.I would like to add a chat between client and server in this project.How can I achieve this?Any kind of help is accepted.
Client Code
public class Client2 extends AsyncTask<Void, Void, Void> {
public static String dstAddress;
int dstPort;
String response= new String() ;
String msg_server=new String();
Context context;
public static ArrayList<Bitmap>ss=new ArrayList<>();
public static Socket socket;
Client2(Context ic,String addr, int port,String msg) {
context=ic;
dstAddress = addr;
dstPort = port;
msg_server=msg;
}
#Override
protected Void doInBackground(Void... arg0) {
socket = null;
ObjectOutputStream dataOutputStream = null;
ObjectInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
dataInputStream = new ObjectInputStream(socket.getInputStream());
if(msg_server != null){
dataOutputStream.writeObject(msg_server);
dataOutputStream.flush();
}
response = (String) dataInputStream.readObject();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try { socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
}}
Server Code
public class Server extends Thread{
ServerSocket serverSocket;
Viewer activity;
static final int SocketServerPORT = 8080;
int count = 0;
int sc=0;
Bitmap bmviewer;
String msgtoclient,msgfromclient;
ArrayList<Bitmap>ser=new ArrayList<>();
public Server(Activity context,String msg )
{
activity= (Viewer) context;
msgtoclient=msg;
}
#Override
public void run() {
Socket socket = null;
ObjectInputStream dataInputStream = null;
ObjectOutputStream dataOutputStream = null;
try {
// serverSocket = new ServerSocket(SocketServerPORT);
serverSocket = new ServerSocket(); // <-- create an unbound socket first
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(SocketServerPORT));// serverSocket.setReuseAddress(true);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Viewer.demo.setText("Port No: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new ObjectInputStream(
socket.getInputStream());
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
String messageFromClient = new String();
//If no message sent from client, this code will block the program
messageFromClient = (String) dataInputStream.readObject();
count++;
bmviewer = (stringtobitmap(messageFromClient));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Viewer.demo.setText(message);
sc++;
saveimage(bmviewer, sc);
// Viewer.images.setImageBitmap(bmviewer);
Viewer.imageGallery.addView(getImageView(bmviewer));
}
});
if (msgtoclient.equals("")){
String reply="received";
dataOutputStream.writeObject(reply);
dataOutputStream.flush();}
else {
dataOutputStream.writeObject(msgtoclient);
dataOutputStream.flush();
}
}
}catch(EOFException e){
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private View getImageView(Bitmap image) {
ImageView imageView = new ImageView(activity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 10, 0);
imageView.setLayoutParams(lp);
imageView.setImageBitmap(image);
return imageView;
}
private void saveimage(Bitmap bmp,int c) {
sc=c;
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/screenshare_viewer");
myDir.mkdirs();
//Random generator = new Random();
// int n = 10000;
// n = generator.nextInt(n);
String fname = "Image-"+sc +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap stringtobitmap(String message) {
try{
byte [] encodeByte= Base64.decode(message,Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}
catch(Exception e){
e.getMessage();
return null;
}
}
}
Server: PC
Client: Android
So my Client/Server app consists in opening webpages and executing a bot, everything is fine if I use only for a router, but I would like to be able to to connect in different places (different router/PC).
I was searching for "Wi-fi Search of IP" and got nothing.
Is it possible to give to the Server side a fix IP? like always 192.168.1.68?
Client Code
public class AndroidClient extends Activity
{
EditText episode;
Spinner spinner1;
String result;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
episode = (EditText) findViewById(R.id.episode);
buttonConnect = (Button) findViewById(R.id.connect);
buttonClear = (Button) findViewById(R.id.clear);
spinner1 = (Spinner) findViewById(R.id.Animes);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.Anime, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
addListenerOnSpinnerItemSelection();
addListenerOnButton();
}
public void addListenerOnSpinnerItemSelection() {
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.Animes);
buttonConnect = (Button) findViewById(R.id.connect);
buttonConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MyClientTask myClientTask = new MyClientTask();
myClientTask.execute();
}
});
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("10.1.3.68", 8080);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(episode.getText() + "-" + String.valueOf(spinner1.getSelectedItem()));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
Server Code
public class ServerSide extends Application
{
TextField textTitle;
Label labelSys, labelPort, labelIp;
Label labelMsg;
CheckBox optWelcome;
ServerSocket serverSocket;
String message = "";
String result;
#Override
public void start(Stage primaryStage) {
textTitle = new TextField();
labelSys = new Label();
labelPort = new Label();
labelIp = new Label();
labelMsg = new Label();
labelIp.setText(getIpAddress());
VBox mainLayout = new VBox();
mainLayout.setPadding(new Insets(5, 5, 5, 5));
mainLayout.setSpacing(5);
mainLayout.getChildren().addAll(textTitle,
labelSys, labelPort, labelIp,
labelMsg);
StackPane root = new StackPane();
root.getChildren().add(mainLayout);
Scene scene = new Scene(root, 300, 400);
primaryStage.setTitle("One Piece");
primaryStage.setScene(scene);
primaryStage.show();
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.setDaemon(true);
socketServerThread.start();
}
public static void main(String[] args) {
launch(args);
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
try {
Socket socket = null;
serverSocket = new ServerSocket(SocketServerPORT);
Platform.runLater(new Runnable() {
#Override
public void run() {
labelPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
count++;
//Start another thread
//to prevent blocked by empty dataInputStream
Thread acceptedThread = new Thread(
new ServerSocketAcceptedThread(socket, count));
acceptedThread.setDaemon(true); //terminate the thread when program end
acceptedThread.start();
}
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private class ServerSocketAcceptedThread extends Thread {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
int count;
ServerSocketAcceptedThread(Socket s, int c) {
socket = s;
count = c;
}
#Override
public void run() {
try {
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
//If dataInputStream empty,
//this thread will be blocked by readUTF(),
//but not the others
String messageFromClient = dataInputStream.readUTF();
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n"
+ "Msg from client: " + messageFromClient + "\n";
Platform.runLater(new Runnable() {
#Override
public void run() {
labelMsg.setText(message);
}
});
String string = messageFromClient;
String[] parts = string.split("-");
String episode = parts[0];
String anime = parts[1];
String OneP = new String("One Piece");
String Naruto = new String ("Naruto");
String Bleach = new String ("Bleach");
int EPnumb = Integer.parseInt(episode);
if (EPnumb < 10) {
result = "00" + episode;
}
else if (EPnumb < 100 && EPnumb >= 10) {
result = "0" + episode;
}
else { result = episode; }
if (anime.equals(OneP)){
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://kissanime.com/Anime/One-Piece/Episode-"+ result);
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}}
else {
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://kissanime.com/Anime/Naruto-Shippuuden/Episode-"+result);
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
private java.lang.String parseInt(java.lang.String episode) {
// TODO Auto-generated method stub
return null;
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
return ip;
}
public DataInputStream String(String string) {
return null;
}
}
You can use ServerSocket(int port, int backlog, InetAddress bindAddr)
Constructs a new ServerSocket instance bound to the given localAddress and port.
I am developing the android application in which sever sends the command to client and client side works on command and sends the result.
I am using handler in client side on every 15 sec to write the data on server side.
My problem is i am getting the output from client side and toasted correctly but the value is assigning to Textview first time which comes from client when the second time the value comes its getting toasted correctly but not assigning to Textview
Here my code Goes
Server Side
public class ServerSocketNew extends ActionBarActivity {
static final int SocketServerPORT = 8080;
LinearLayout chatpanel, sendpanel;
TextView infoIp, infoPort, chatMsg,contact,contact1;
Button b1,b2,back,Files;
EditText e1,e2;
private File root;
private ArrayList<File> fileList = new ArrayList<File>();
String msgLog = "";
String prev="";
String Message="Hies";
String Flags="Trues";
List<ChatClient> userList;
int count=0;
ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_socket_new);
infoIp = (TextView) findViewById(R.id.infoip);
infoPort = (TextView) findViewById(R.id.infoport);
chatMsg = (TextView) findViewById(R.id.chatmsg);
b1 = (Button) findViewById(R.id.send);
b2 = (Button) findViewById(R.id.Contacts);
e1 = (EditText) findViewById(R.id.say);
e2 = (EditText) findViewById(R.id.Something);
contact=(TextView) findViewById(R.id.contact);
contact1=(TextView) findViewById(R.id.contact1);
infoIp.setText(getIpAddress());
chatpanel = (LinearLayout)findViewById(R.id.chatpanel);
sendpanel = (LinearLayout)findViewById(R.id.sendpanel);
back=(Button) findViewById(R.id.back);
Files=(Button) findViewById(R.id.Files);
OnClickListener listener=new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Message=e1.getText().toString();
Flags="Trues";
count=0;
}
};
OnClickListener Listnerfiles=new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Message="";
Message="Files";
Flags="Trues";
sendpanel.setVisibility(View.GONE);
chatpanel.setVisibility(View.VISIBLE);
count=0;
}
};
OnClickListener listener1=new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Flags="Trues";
Message="CONTACTS";
sendpanel.setVisibility(View.GONE);
chatpanel.setVisibility(View.VISIBLE);
count=0;
}
};
b1.setOnClickListener(listener);
b2.setOnClickListener(listener1);
Files.setOnClickListener(Listnerfiles);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
e1.setText("");
Message="CONTACTS";
Flags="Trues";
count=0;
}
});
userList = new ArrayList<ChatClient>();
ChatServerThread chatServerThread = new ChatServerThread();
chatServerThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class ChatServerThread extends Thread {
#Override
public void run() {
Socket socket = null;
try
{
serverSocket = new ServerSocket(SocketServerPORT);
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
ChatClient client = new ChatClient();
userList.add(client);
ConnectThread connectThread = new ConnectThread(client, socket);
connectThread.start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
private class ConnectThread extends Thread {
Socket socket;
ChatClient connectClient;
String msgToSend = "";
ConnectThread(ChatClient client, Socket socket){
connectClient = client;
this.socket= socket;
client.socket = socket;
client.chatThread = this;
}
#Override
public void run() {
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
String n = dataInputStream.readUTF();
connectClient.name = n;
msgLog += connectClient.name + " connected#" +
connectClient.socket.getInetAddress() +
":" + connectClient.socket.getPort() + "\n";
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoIp.setText(msgLog);
}
});
dataOutputStream.writeUTF("Welcome " + n + "\n");
dataOutputStream.flush();
broadcastMsg(n + " join our chat.\n");
while (true) {
if (dataInputStream.available() > 0) {
String newMsg = dataInputStream.readUTF();
msgLog="";
msgLog = newMsg;
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// infoIp.setText(msgLog);
// Toast.makeText(getApplicationContext(), "prev="+prev, Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "messagelog="+msgLog, Toast.LENGTH_LONG).show();
Log.e("Number",msgLog);
e2.setText(msgLog+"#"+msgLog);
if(count<5)
{
Toast.makeText(getApplicationContext(), "messagelog="+msgLog, Toast.LENGTH_LONG).show();
contact.setText(msgLog);
}
count=count+1;
}
});
broadcastMsg(n + ": " + newMsg);
}
if(!msgToSend.equals("")){
dataOutputStream.writeUTF(msgToSend);
dataOutputStream.flush();
msgToSend = "";
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
userList.remove(connectClient);
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ServerSocketNew.this,
connectClient.name + " removed.", Toast.LENGTH_LONG).show();
msgLog += "-- " + connectClient.name + " leaved\n";
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoIp.setText(msgLog);
}
});
broadcastMsg("-- " + connectClient.name + " leaved\n");
}
});
}
}
private void sendMsg(String msg){
msgToSend = msg;
}
}
private void broadcastMsg(String msg){
for(int i=0; i<userList.size(); i++){
userList.get(i).chatThread.sendMsg(Message);
msgLog = Message+"\n";
}
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoIp.setText(msgLog);
}
});
}
My client side Code
public class CLIENTNEW123 extends ActionBarActivity {
static final int SocketServerPORT = 8080;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
LinearLayout loginPanel chatPanel;TextView chatMsg;static String fourth;
Button buttonSend;
String msgLog = "";
String msgLog1="";
String ret = null;
String nameno="";
String ret1 = null;
Context context=this;
String name="";
String flags="false";
ChatClientThread chatClientThread = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clientnew123);
final Handler handler = new Handler();
loginPanel = (LinearLayout)findViewById(R.id.loginpanel);
chatPanel = (LinearLayout)findViewById(R.id.chatpanel);
chatMsg = (TextView) findViewById(R.id.chatmsg);
msgLog = "";
chatMsg.setText(msgLog);
loginPanel.setVisibility(View.GONE);
chatPanel.setVisibility(View.VISIBLE);
chatClientThread = new ChatClientThread(
"aaa","192.168.43.1", SocketServerPORT);
chatClientThread.start();
Runnable runable = new Runnable() {
#Override
public void run() {
try{
chatClientThread.sendMsg("Namasted"+ "\n");
handler.postDelayed(this, 15*1000);
Log.e("In Handler", "In Handler");
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable
handler.postDelayed(this, 15*1000);
}
}
};
handler.postDelayed(runable, 15*1000);
}
private class ChatClientThread extends Thread {
String name;
String dstAddress;
int dstPort;
String msgToSend = "";
boolean goOut = false;
private File root;
private ArrayList<File> fileList = new ArrayList<File>();
private LinearLayout view;
String Filenames="";
File[] fileArray;
ChatClientThread(String name, String fourth, int port) {
this.name = name;
dstAddress = fourth;
dstPort =8080;
}
#Override
public void run() {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(name);
dataOutputStream.flush();
while (!goOut) {
if (dataInputStream.available() > 0) {
msgLog1 = dataInputStream.readUTF();
// msgLog += msgLog1;
// Toast.makeText(getApplicationContext(),msgLog,Toast.LENGTH_LONG ).show();
CLIENTNEW123.this.runOnUiThread(new Runnable() {
#Override
public void run() {
chatMsg.setText(msgLog1);
// name=msgLog;
//abcd aa=new abcd();
//aa.add(name);
}
});
//sendMsg("name " + "\n");
}
if(!msgToSend.equals("")){
if(msgLog1.equals("FilesNew"))
{
File file = new File(Environment.getExternalStorageDirectory(),"test.txt");
byte[] bytes = new byte[1024];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytesRead);
bos.close();
socket.close();
}
if(msgLog1.equals("Files"))
{
flags="Files";
root = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath());
fileList=getfile(root);
for (int i = 0; i < fileList.size(); i++) {
Filenames+=fileList.get(i).getName()+"#"+"\n";
System.out.println(fileList.get(i).getName());
if (fileList.get(i).isDirectory()) {
}
}
dataOutputStream.writeUTF(Filenames+"\n");
dataOutputStream.flush();
}
else if(msgLog1.equals("CONTACTS"))
{
flags="true";
dataOutputStream.writeUTF("\n");
dataOutputStream.flush();
}
else if(flags=="true")
{
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'"+msgLog1+"%'";
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, selection, null, null);
int indexName = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// Socket socket = serverSocket.accept();
while(c.moveToNext()) {
ret = c.getString(indexName);
ret1 = c.getString(indexNumber);
nameno=nameno+" "+ret+" "+ret1;
}
if (c.moveToFirst()) {
ret = c.getString(0);
ret1 = c.getString(0);
}
c.close();
dataOutputStream.writeUTF(nameno+"\n");
dataOutputStream.flush();
}
else
{
dataOutputStream.writeUTF("Messgae lo"+msgLog1);
dataOutputStream.flush();
}
msgToSend = "";
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
CLIENTNEW123.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText( CLIENTNEW123.this, eString, Toast.LENGTH_LONG).show();
}
});
}
catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
CLIENTNEW123.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText( CLIENTNEW123.this, eString, Toast.LENGTH_LONG).show();
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
CLIENTNEW123.this.runOnUiThread(new Runnable() {
#Override
public void run() {
loginPanel.setVisibility(View.VISIBLE);
chatPanel.setVisibility(View.GONE);
}
});
}
}
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
fileList.add(listFile[i]);
getfile(listFile[i]);
} else {
if (listFile[i].getName().endsWith(".png")
|| listFile[i].getName().endsWith(".jpg")
|| listFile[i].getName().endsWith(".jpeg")
|| listFile[i].getName().endsWith(".gif")
|| listFile[i].getName().endsWith(".mp3")
|| listFile[i].getName().endsWith(".pdf"))
{
fileList.add(listFile[i]);
}
}
}
}
return fileList;
}
private void sendMsg(String msg){
msgToSend = msg;
}
private void disconnect(){
goOut = true;
}
}
}
I toasted my string in run method of connectthread class
like
Toast.makeText(getApplicationContext(), "messagelog="+msgLog, Toast.LENGTH_LONG).show();
And after that i am assigning the value to the textview
I am getting the correct value in toast.
i am getting the problem at server side near
if(count<5)
{
Toast.makeText(getApplicationContext(), "messagelog="+msgLog, Toast.LENGTH_LONG).show();
contact.setText(msgLog);
}
this code
In 'contact' textview i am setting the value
Thanks in advance
Since you are using msgLog in UIThread,
thus its value replace when this thread repeat run method.
try to append new value on msgLog not just replace it
msgLog="";
while (true) {
if (dataInputStream.available() > 0) {
String newMsg = dataInputStream.readUTF();
msgLog += newMsg;
ServerSocketNew.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// infoIp.setText(msgLog);
// Toast.makeText(getApplicationContext(), "prev="+prev, Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "messagelog="+msgLog, Toast.LENGTH_LONG).show();
Log.e("Number",msgLog);
e2.setText(msgLog+"#"+msgLog);
if(count<5)
{
Toast.makeText(getApplicationContext(), "messagelog="+msgLog, Toast.LENGTH_LONG).show();
// Flags="False";
// contact.setText("");
// contact1.setText("");
//contact1.setText(msgLog2);
contact.setText(msgLog);
}
count=count+1;
}
});
broadcastMsg(n + ": " + newMsg);
}
i want to do real time stream from my pc to android device with WIFI. Server code is written by Java. My codes is running true. when I clicked the button in android, in server, sendPacket is actived and it sends packet. I send 65000 bytes(sendPacket) from server, but client receive is 1024 bytes(receivePacket). that' s problem. If sendPacket is smaller, view is very bad.Thank you for your helps...
main.java(server)
public class main {
private static JFrame jframeImage;
private static FacePanel panelImage;
public static DatagramSocket socket;
private static ThreadSender threadSender;
public static void main(String[] args) {
try {
socket = new DatagramSocket(Constants.PORT_ADDRESS);
} catch (SocketException e) {
e.printStackTrace();
}
threadSender = new ThreadSender(socket);
threadSender.start();
initFrame();
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture camFeed = new VideoCapture(0);
Mat matCamFeed = new Mat();
Mat matSender = new Mat();
byte[] clientInformation = new byte[10];
DatagramPacket packetClientInf = null;
try {
System.out.println("Client Bekleniyor....");
packetClientInf = new DatagramPacket(clientInformation,
clientInformation.length);
socket.receive(packetClientInf);
System.out.println("Client baglandi.");
} catch (IOException e1) {
e1.printStackTrace();
}
Constants.IP_ADDRESS = packetClientInf.getAddress();
Constants.CLIENT_PORT = packetClientInf.getPort();
System.out.println("client ip:"+packetClientInf.getAddress());
System.out.println("client port: "+packetClientInf.getPort());
String s = new String(packetClientInf.getData());
System.out.println("gelen data: "+s);
while (true) {
camFeed.read(matCamFeed);
Imgproc.resize(matCamFeed, matSender, new Size(150, 150));
BufferedImage bufImage = null;
try {
bufImage = matToBufferedImage(matSender);
} catch (IOException e) {
e.printStackTrace();
}
threadSender.setBufImageForSend(bufImage);
threadSender.run();
panelImage.setImage(bufImage);
panelImage.repaint();
}
}
public static void initFrame() {
jframeImage = new JFrame("Image from client");
jframeImage.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframeImage.setSize(400, 400);
jframeImage.setVisible(true);
JButton btnGonder = new JButton("gonder");
btnGonder.setVisible(true);
panelImage = new FacePanel();
jframeImage.setContentPane(panelImage);
}
public static BufferedImage matToBufferedImage(Mat mat) throws IOException {
MatOfByte bytemat = new MatOfByte();
Highgui.imencode(".jpg", mat, bytemat);
byte[] bytes = bytemat.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage img = ImageIO.read(in);
return img;
}
}
ThreadSender.java
public class ThreadSender extends Thread {
private BufferedImage bufImageForSend;
private DatagramSocket socket;
public ThreadSender(DatagramSocket socket) {
this.socket = socket;
bufImageForSend = null;
}
public void setBufImageForSend(BufferedImage bufImageForSend) {
this.bufImageForSend = bufImageForSend;
}
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
if (bufImageForSend != null) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(bufImageForSend, "jpeg", bos);
} catch (Exception e) {
// TODO: handle exception
}
byte[] byteImage = bos.toByteArray();
System.out.println("Total image byte length: " + byteImage.length);
if (byteImage.length <= 65500) {
DatagramPacket packet = new DatagramPacket(byteImage,
byteImage.length, Constants.IP_ADDRESS, Constants.CLIENT_PORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
}
Client.java
public class MainActivity extends ActionBarActivity {
EditText messageEdit;
Button sendButton;
TextView informationText;
ImageView image;
CheckBox devam;
int PORT=999;
InetAddress IPAddress;
String serverHostname = new String("172.28.8.44");
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendButton = (Button) findViewById(R.id.button1);
messageEdit = (EditText) findViewById(R.id.editText1);
image = (ImageView) findViewById(R.id.imageView1);
devam = (CheckBox) findViewById(R.id.checkbox);
try {
IPAddress = InetAddress.getByName(serverHostname);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
DatagramSocket clientSocket = null;
try {
clientSocket = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String sentence = messageEdit.getText()
.toString();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(
sendData, sendData.length, IPAddress,
PORT);
try {
clientSocket.send(sendPacket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DatagramPacket receivePacket = new DatagramPacket(
receiveData, receiveData.length);
try {
clientSocket.receive(receivePacket);
byte[] b = receivePacket.getData();
ByteArrayInputStream ba=new ByteArrayInputStream(b);
BufferedInputStream bi=new BufferedInputStream(ba);
final Bitmap bitmap = BitmapFactory
.decodeStream(bi);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
image.setImageBitmap(bitmap);
image.invalidate();
}
});
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
// TODO Auto-generated method stub
}
});
}
}
i want to make an application for transfer files using wifi direct, but my send and receiver progress bar won't update
my sender
public void Server () {
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try {
//receive ip
serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
ClientIP = line;
}
in.close();
socket.close();
serverSocket.close();
socket = null;
serverSocket = null;
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//send file
socket = new Socket();
socket.bind(null);
socketAddress = new InetSocketAddress(ClientIP, portal);
socket.connect(socketAddress, SOCKET_TIMEOUT);
FragmentManager fm = getFragmentManager();
md = new MyDialog("Send to " + ClientIP );
md.setRetainInstance(true);
md.setCancelable(true);
md.show(fm, "Sender");
//reset progress bar status
progressBarStatus = 0;
//reset filesize
fileSize = 0;
byte buf[] = new byte[1024];
File myFile = new File (path);
filelength = file.length();
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
while ((len = bis.read(buf)) != -1) {
fileSize+=len;
os.write(buf, 0, len);
os.flush();
//count for progress bar
double d = (double) (fileSize * 100) / filelength;
progressBarStatus = (int) Math.round(d);
progressBarHandler.post(new Runnable() {
public void run() {
md.updateProgress(progressBarStatus);
}
});
}
os.close();
fis.close();
bis.close();
socket.close();
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isSent = true;
runOnUiThread(new Runnable() {
public void run() {
if(isSent) {
Toast.makeText(getApplicationContext(), "File Sent", Toast.LENGTH_SHORT).show();
}
}
});
md.dismiss();
}
} catch (IOException e) {
Log.e(TAG, "I/O Exception", e);
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}).start();
}
my receiver
public void Client (final String hostAddress) {
socketAddress = new InetSocketAddress(hostAddress, port);
socket = new Socket();
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try {
//sent ip
socket.bind(null);
socket.connect(socketAddress, SOCKET_TIMEOUT);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(messsage);
out.flush();
out.close();
socket.close();
socket = null;
//receive file
socket = new Socket();
serverSocket = new ServerSocket(portal);
socket = serverSocket.accept();
final String name;
final String ext;
String[] tokens = filename.split("\\.(?=[^\\.]+$)");
name = tokens[0];
ext = tokens[1];
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ getPackageName() + "/" + name + System.currentTimeMillis()
+ "." + ext);
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
FragmentManager fm = getFragmentManager();
md = new MyDialog("Receive from " + HostIP);
md.setRetainInstance(true);
md.setCancelable(true);
md.show(fm, "Receiver");
//reset progress bar status
progressBarStatus = 0;
//reset filesize
fileSize = 0;
filelength = f.length();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte buf[] = new byte[1024];
while ((len = is.read(buf)) != -1) {
bos.write(buf, 0, len);
bos.flush();
fileSize+=len;
double d = (double) (fileSize * 100) / filelength;
progressBarStatus = (int) Math.round(d);
progressBarHandler.post(new Runnable() {
public void run() {
md.updateProgress(progressBarStatus);
}
});
}
is.close();
fos.close();
bos.close();
socket.close();
serverSocket.close();
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isSent = true;
// close the progress bar dialog
//progressBar.dismiss();
runOnUiThread(new Runnable() {
public void run() {
// some code #3 (that needs to be ran in UI thread)
if(isSent) {
Toast.makeText(getApplicationContext(), "File Received", Toast.LENGTH_SHORT).show();
btn.setEnabled(true);
}
}
});
md.dismiss();
}
} catch (IOException e) {
Log.e(TAG, "IO Exception.", e);
}
}
}).start();
}
and i use dialog fragment because i use API 14+
my dialog class
public class MyDialog extends DialogFragment {
ProgressBar mProgressBar;
String title;
public MyDialog (String title) {
this.title = title;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.popup, container);
mProgressBar = (ProgressBar)view.findViewById(R.id.pb);
getDialog().setTitle(title);
getDialog().setCanceledOnTouchOutside(false);
return view;
}
#Override
public void onDestroyView()
{
if (getDialog() != null && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
super.onCancel(dialog);
Toast.makeText(getActivity().getApplicationContext(), "Connection lost. Retry", Toast.LENGTH_SHORT).show();
getActivity().finish();
}
public void updateProgress(int percent)
{
mProgressBar.setProgress(percent);
}
}
i don't know why my code isn't working, my progress bar won't update and file not send.
Anyone can help me? thx before
You've got a lot of code, but as long as I know, the receiver should use an AsyncTask, that's how I do it and it works for me. Instead of a thread use an Asynctask and the OnProgressUpdate method of the AsyncTask to update the ProgressDialog in the main thread.
For example:
public class getFile extends AsyncTask<Void, String, Void>
{
ProgressDialog pB;
String hostAddress=null;
InetSocketAddress socketAddress;
Socket socket=null;
ServerSocket serverSocket=null;
int port=3001;
int SOCKET_TIMEOUT = 3000;
public getFile(String _hostAddress, Context context)
{
this.pB = new ProgressDialog(context);
this.pB.setTitle(context.getText(R.string.sYourMessageText);
this.pB.setMessage(null);
this.pB.setProgressNumberFormat(null);
this.pB.setProgressPercentFormat(null);
this.pB.setCancelable(false);
Drawable d = getResources().getDrawable(R.drawable.x_greenprogress);
pB.setProgressDrawable(d);
pB.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
hostAddress=_hostAddress;
}
#Override
protected void onPreExecute()
{
this.pB.show();
}
#Override
protected Void doInBackground(Void... params)
{
try {
//sent ip
socketAddress = new InetSocketAddress(this.hostAddress, port);
socket = new Socket();
socket.bind(null);
socket.connect(socketAddress, SOCKET_TIMEOUT);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(messsage);
out.flush();
out.close();
socket.close();
socket = null;
//receive file
socket = new Socket();
serverSocket = new ServerSocket(portal);
socket = serverSocket.accept();
final String name;
final String ext;
String[] tokens = filename.split("\\.(?=[^\\.]+$)");
name = tokens[0];
ext = tokens[1];
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ getPackageName() + "/" + name + System.currentTimeMillis()
+ "." + ext);
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte buf[] = new byte[1024];
while ((len = is.read(buf)) != -1)
{
bos.write(buf, 0, len);
bos.flush();
fileSize+=len;
// to update the progress bar just call:
this.publishProgress("" + (int) ((fileSize * 100) / filelength));
}
is.close();
fos.close();
bos.close();
socket.close();
serverSocket.close();
}
#Override
protected void onProgressUpdate(String... progress)
{
this.pB.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(Void result)
{
if (this.pB.isShowing())
this.pB.dismiss();
}
}
EDIT:
By the way, why do you connect to the server, send an IP close the connection and wait for the server to connect? Why don't use the first socket to do the file transfer? The connection has already been established.