I'm working in a remote ScreenRecord in real time based in this code.
With this code of reference i'm able to record screen of my smartphone with success and saving .mp4 file in some folder previous defined.
But to my project, i need that this content be sent to server (similar to Team View for android).
My last attempt to sent this content to server side was like this:
OutputStream os = clientSocket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream (os);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(encodedData);
oos.flush();
bos.flush();
os.flush();
Reference => this question
but comes a error of:
java.io.NotSerializableException
in this line > oos.writeObject(encodedData);
Then, i want know how solve it or some other way to make this task.
Here is complete code:
/////////////////////////////////////// CLIENTSOCKET ///////////////////////////////////////////
Socket clientSocket;
int SERVERPORT = 60;
String SERVER_IP = "192.168.15.6";
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
clientSocket = new Socket(serverAddr, SERVERPORT);
new Thread(new CommsThread()).start();
} catch (Exception e1) {
System.out.println(e1.toString());
}
}
}
class CommsThread implements Runnable {
#Override
public void run() {
try {
System.out.println("Waiting for server request");
while(clientSocket.isConnected()){
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())),true);
if (reader.ready()) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
if(line != null && !line.trim().isEmpty()) {
if(line.equalsIgnoreCase("screenrecord")){
System.out.println(out.toString());
mMediaProjectionManager = (MediaProjectionManager)getSystemService(android.content.Context.MEDIA_PROJECTION_SERVICE);
Intent permissionIntent = mMediaProjectionManager.createScreenCaptureIntent();
startActivityForResult(permissionIntent, REQUEST_CODE_CAPTURE_PERM);
out.flush();
}
if(line.equalsIgnoreCase("exit")) {
stopRecording();
break;
}
}
}
}
Thread.sleep(100);
}
System.out.println("Shutting down Socket!!");
clientSocket.close();
} catch (Exception e1) {
System.out.println(e1.toString());
}
}
}
////////////////////////////////////// MEDIAPROJECTION /////////////////////////////////////////
private static final int REQUEST_CODE_CAPTURE_PERM = 1234;
private static final String VIDEO_MIME_TYPE = "video/avc";
int VIDEO_WIDTH, VIDEO_HEIGHT;
private boolean mMuxerStarted = false;
private MediaProjectionManager mMediaProjectionManager;
private MediaProjection mMediaProjection;
private Surface mInputSurface;
private MediaMuxer mMuxer;
private MediaCodec mVideoEncoder;
private MediaCodec.BufferInfo mVideoBufferInfo;
private int mTrackIndex = -1;
private final Handler mDrainHandler = new Handler(Looper.getMainLooper());
private Runnable mDrainEncoderRunnable = new Runnable() {
#Override
public void run() {
drainEncoder();
}
};
public void stopRecording(){
releaseEncoders();
}
private void startRecording() {
DisplayManager dm = (DisplayManager)getSystemService(Context.DISPLAY_SERVICE);
Display defaultDisplay = dm.getDisplay(Display.DEFAULT_DISPLAY);
if (defaultDisplay == null) {
throw new RuntimeException("No display found.");
}
DisplayMetrics metrics = getResources().getDisplayMetrics();
int screenWidth = metrics.widthPixels;
int screenHeight = metrics.heightPixels;
int screenDensity = metrics.densityDpi;
VIDEO_WIDTH = screenWidth;
VIDEO_HEIGHT = screenHeight;
prepareVideoEncoder();
mMediaProjection.createVirtualDisplay("Recording Display", screenWidth, screenHeight, screenDensity, 0, mInputSurface, null, null);
drainEncoder();
}
private void prepareVideoEncoder() {
mVideoBufferInfo = new MediaCodec.BufferInfo();
MediaFormat format = MediaFormat.createVideoFormat(VIDEO_MIME_TYPE, VIDEO_WIDTH, VIDEO_HEIGHT);
int frameRate = 30;
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
format.setInteger(MediaFormat.KEY_BIT_RATE, 6000000);
format.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate);
format.setInteger(MediaFormat.KEY_CAPTURE_RATE, frameRate);
format.setInteger(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, 1000000 / frameRate);
format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
try {
mVideoEncoder = MediaCodec.createEncoderByType(VIDEO_MIME_TYPE);
mVideoEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mInputSurface = mVideoEncoder.createInputSurface();
mVideoEncoder.start();
} catch (IOException e) {
releaseEncoders();
}
}
private boolean drainEncoder() {
mDrainHandler.removeCallbacks(mDrainEncoderRunnable);
while (true) {
int bufferIndex = mVideoEncoder.dequeueOutputBuffer(mVideoBufferInfo, 0);
if (bufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
break;
} else if (bufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
} else if (bufferIndex < 0) {
} else {
ByteBuffer encodedData = mVideoEncoder.getOutputBuffer(bufferIndex);
if (encodedData == null) {
throw new RuntimeException("couldn't fetch buffer at index " + bufferIndex);
}
if ((mVideoBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
mVideoBufferInfo.size = 0;
}
if (mVideoBufferInfo.size != 0) {
encodedData.position(mVideoBufferInfo.offset);
encodedData.limit(mVideoBufferInfo.offset + mVideoBufferInfo.size);
try {
OutputStream os = clientSocket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream (os);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(encodedData);
oos.flush();
bos.flush();
os.flush();
} catch (IOException e) {
throw new RuntimeException("couldn't send data to server");
}
} else {
}
mVideoEncoder.releaseOutputBuffer(bufferIndex, false);
}
if ((mVideoBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
break;
}
}
mDrainHandler.postDelayed(mDrainEncoderRunnable, 10);
return false;
}
private void releaseEncoders() {
mDrainHandler.removeCallbacks(mDrainEncoderRunnable);
if (mMuxer != null) {
if (mMuxerStarted) {
mMuxer.stop();
}
mMuxer.release();
mMuxer = null;
mMuxerStarted = false;
}
if (mVideoEncoder != null) {
mVideoEncoder.stop();
mVideoEncoder.release();
mVideoEncoder = null;
}
if (mInputSurface != null) {
mInputSurface.release();
mInputSurface = null;
}
if (mMediaProjection != null) {
mMediaProjection.stop();
mMediaProjection = null;
}
mVideoBufferInfo = null;
mDrainEncoderRunnable = null;
mTrackIndex = -1;
}
////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (REQUEST_CODE_CAPTURE_PERM == requestCode) {
if (resultCode == RESULT_OK) {
mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, intent);
startRecording();
} else {
}
}
}
Related
I'm trying to capture an image via camera2 API, and i'm able to achieve it.
But the main problem is when i try to open that image on mobile phone it shows an error like "unsupported file format". Here's my code so far.
SimpleDateFormat s = new SimpleDateFormat("ddhhmmss");
String format = s.format(new Date());
private File file = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES)+"/"+"image_" + format + ".jpg");
protected void takePicture() {
if(null == cameraDevice) {
Log.e("tag", "cameraDevice is null");
return;
}
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
Size[] jpegSizes = null;
if (characteristics != null) {
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
}
int width = 640;
int height = 480;
if (jpegSizes != null && 0 < jpegSizes.length) {
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
List<Surface> outputSurfaces = new ArrayList<Surface>(2);
outputSurfaces.add(reader.getSurface());
outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(reader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
// Orientation
int rotation = getWindowManager().getDefaultDisplay().getRotation();
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(CaptureImage.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
createCameraPreview();
}
};
cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(CameraCaptureSession session) {
try {
session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onConfigureFailed(CameraCaptureSession session) {
}
}, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
try {
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
save(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (image != null) {
image.close();
}
}
}
private void save(byte[] bytes) throws IOException {
OutputStream output = null;
try {
output = new FileOutputStream(file);
output.write(bytes);
} finally {
if (null != output) {
output.close();
}
}
}
};
I'm using socket to create http socket server on Java android application.
Send and Get headers from client and server I'm getting fast. But get when trying read http body it takes a long time... why ?
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
public void run() {
try {
runProxy();
}catch (Throwable t){
}
};
}).start();
}
private void runProxy() throws Throwable{
try {
ServerSocket ss = new ServerSocket(8080);
while (true) {
Socket s = ss.accept();
System.err.println("Client accepted");
new Thread(new TestProxy(s)).start();
}
}catch (IOException e){
}
}
TestProxy.class
public class TestProxy implements Runnable{
private Socket s, c;
private InputStream is;
private OutputStream os;
ArrayList<String> requestList;
ArrayList<String> responseList;
private BufferedReader br;
public TestProxy(Socket s) throws Throwable{
this.s = s;
this.is = s.getInputStream();
this.os = s.getOutputStream();
this.requestList = new ArrayList<String>();
this.responseList = new ArrayList<String>();
this.run();
}
public void run(){
try {
this.readRequest();
this.forwardRequest();
this.forwardResponse(); //<--- this is trouble ??!
}catch (Throwable e){
}finally {
/*try {
s.close();
c.close();
}catch (IOException e) {}*/
}
}
private void readRequest() throws Throwable{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//int lengthBody = 0;
while(true) {
String s = br.readLine();
requestList.add(s + "\r\n");
/*if (s.startsWith("Content-Length: ")) { // get the
// content-length
int index = s.indexOf(':') + 1;
String len = s.substring(index).trim();
lengthBody = Integer.parseInt(len);
}*/
if(s == null || s.trim().length() == 0) {
break;
}
}
is.close();
}
private void forwardRequest(){
String firstSectionInProtocol = requestList.get(0); //GET http://example.com/?d=d HTTP/1.1
Pattern p = Pattern.compile("^\\w+\\s+(\\S+)");
Matcher m = p.matcher(firstSectionInProtocol);
if(m.find()) {
String URI = m.group(1); //http://example.com/?d=d
try {
URL aURL = new URL(URI);
try {
c = new Socket(aURL.getHost(), 80);
final OutputStream outToServer = c.getOutputStream();
String firstSection = "GET "+aURL.getFile()+" HTTP/1.1\r\n";
outToServer.write(firstSection.getBytes());
System.out.println(firstSection);
for(int i = 1; i < requestList.size(); i++){
outToServer.write(requestList.get(i).getBytes());
System.out.println(requestList.get(i));
}
outToServer.flush();
}catch (IOException e) {
}
}catch (MalformedURLException e){ }
}
}
private void forwardResponse() throws Throwable{
final InputStream inFromServer = c.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inFromServer));
int lengthBody = 0;
while(true) {
String s = br.readLine();
System.out.println( s + "\r\n" );
if (s.startsWith("Content-Length: ")) { // get the
// content-length
int index = s.indexOf(':') + 1;
String len = s.substring(index).trim();
lengthBody = Integer.parseInt(len);
}
if(s.equals("")) {
break;
}
}
//
// Processing long time
//
if (lengthBody > 0) {
int read;
StringBuilder body = new StringBuilder();
while ((read = br.read()) != -1) {
body.append((char) read);
if (body.length() >= lengthBody)
break;
}
System.out.println(body.toString());
}
}
}
in the method forwardResponse(); i trying get a body response.
while(true) {
String s = br.readLine();
System.out.println( s + "\r\n" );
/*if (s.startsWith("Content-Length: ")) { // get the
// content-length
int index = s.indexOf(':') + 1;
String len = s.substring(index).trim();
lengthBody = Integer.parseInt(len);
}*/
if(s == null) {
break;
}
}
Until now I could programmatically copy files from the internal memory of the phone to an USB-OTG connected to it. I just had to give root permissions and edit platform.xml. But now my device (Samsung Galaxy S6 Edge +) has been updated to Android 6 and made my code stop working.
I'm getting this error everytime I try to copy files the way I did before:
Caused by java.lang.RuntimeException: java.io.FileNotFoundException: /mnt/media_rw/4265-1803/requiredfiles/Oculus/360Photos/Pisos/Chalet Anna/R0010008.JPG: open failed: EACCES (Permission denied)
String from = Environment.getExternalStorageDirectory() + File.separator + getString(R.string.FOLDER_SDCARD);
String to = Utils.getUsbPath() + File.separator + getString(R.string.FOLDER_USB);
FileManager fileManager = new FileManager(getActivity(), from, to, false);
fileManager.execute(true);
My getUsbPath function
public static String getUsbPath() {
String finalpath = null;
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
String[] patharray = new String[10];
int i = 0;
int available = 0;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
String mount = new String();
if (line.contains("secure"))
continue;
if (line.contains("asec"))
continue;
if (line.contains("fat")) {// TF card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
mount = mount.concat(columns[1] + "/requiredfiles");
patharray[i] = mount;
i++;
// check directory is exist or not
File dir = new File(mount);
if (dir.exists() && dir.isDirectory()) {
// do something here
available = 1;
finalpath = mount;
break;
} else {
}
}
}
}
if (available == 1) {
} else if (available == 0) {
finalpath = patharray[0];
}
} catch (Exception e) {
}
return finalpath;
}
My FileManager.class
public class FileManager extends AsyncTask<Boolean, Integer, Boolean> {
private Context context;
private String from;
private String to;
private ProgressDialog progressDialog;
private int filesCount=0;
private int filesTotal=0;
Boolean completed;
Boolean move;
MainActivity main;
public static final String TAG = "FileManager";
public FileManager(Context context, String from, String to, Boolean move) {
this.context = context;
this.from = from;
this.to = to;
this.move = move;
this.main = (MainActivity) context;
}
#Override
protected Boolean doInBackground(Boolean... params) {
File source = new File(from);
File target = new File(to);
try {
countFiles(source);
copyDirectory(source, target);
if (move) {
deleteFiles(source);
}
completed = true;
} catch (Exception error) {
Log.e(TAG, "doInBackground", error);
completed = false;
try {
throw error;
} catch (IOException e) {
e.printStackTrace();
}
throw new RuntimeException(error.toString());
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
if (move) {
progressDialog.setMessage(context.getString(R.string.moving_files));
} else {
progressDialog.setMessage(context.getString(R.string.copying_files));
}
progressDialog.setIndeterminate(true);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
progressDialog.dismiss();
if (completed) {
if (move) {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.move_completed), Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.copy_completed), Snackbar.LENGTH_LONG).show();
}
} else {
if (move) {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.move_failed), Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.copy_failed), Snackbar.LENGTH_LONG).show();
}
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setIndeterminate(false);
progressDialog.setMax(filesTotal);
progressDialog.setProgress(filesCount);
}
private void copyDirectory(File sourceLocation, File targetLocation) throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdirs();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
}
} else {
if (!targetLocation.exists()) {
filesCount++;
publishProgress();
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
scanFile(targetLocation.getCanonicalPath(), false);
}
}
}
private void countFiles(File file) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < file.listFiles().length; i++) {
countFiles(new File(file, children[i]));
}
} else {
filesTotal++;
}
}
public void deleteFiles(File folder) {
if (folder.isDirectory()) {
File[] list = folder.listFiles();
if (list != null) {
for (int i = 0; i < list.length; i++) {
File tmpF = list[i];
if (tmpF.isDirectory()) {
deleteFiles(tmpF);
}
tmpF.delete();
String path;
try {
path = tmpF.getCanonicalPath();
} catch (Exception error) {
Log.e(TAG, "", error);
path = tmpF.getAbsolutePath();
}
scanFile(path, true);
}
}
}
}
private void scanFile(String path, final boolean isDelete) {
try {
MediaScannerConnection.scanFile(context, new String[] { path },
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
if (isDelete) {
if (uri != null) {
context.getContentResolver().delete(uri,
null, null);
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
How can I solve it?
I want to send 18 mb Data. It is working. But I have to wait too long that I get Email.
Code:
public void sendEmail()
{
emailSendReceiver = new EmailSendBroadcastReceiver();
EmailSend emailSend = new EmailSend();
emailSend.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public class EmailSend extends AsyncTask<Void, Void, Boolean>
{
#Override
protected Boolean doInBackground(Void... params)
{
boolean bResult = false;
String sDeviceID = configReader.getXmlValue(KEY_ID);
Mail m = new Mail("test#gmail.com", "testpass");
String[] toArr = {"toEmail#gmail.com"};
m.setTo(toArr);
m.setFrom("noreply#something.com");
m.setSubject("device number : "+sDeviceID );
m.setBody("device number : "+sDeviceID);
try
{
String sTxtFileName = sDeviceID+"_"+".txt";
String sFileUrl = Environment.getExternalStorageDirectory().getAbsolutePath()+"/data_source/"+sTxtFileName;
m.addAttachment(sFileUrl);
if(m.send())
{
bResult = true;
}
else
{
// something
}
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
if(result == true)
{
// something
}
}
}
}
The Question is. How can I make it faster? I have 6 AsyncTask. And I don't like to make it with activity.
As suggested by all It would be handy to zip or gzip the file. The same is available in
java.util.zip*
package. Furthermore you could find help for the same here
public void makeZip(String sFile, String zipFileName)
{
FileOutputStream dest = null;
ZipOutputStream out;
byte data[];
FileInputStream fi = null;
int count;
try
{
dest = new FileOutputStream(zipFileName);
out = new ZipOutputStream(new BufferedOutputStream(dest));
data = new byte[BUFFER];
fi = new FileInputStream(sFile);
BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sFile);
out.putNextEntry(entry);
while((count = origin.read(data, 0, BUFFER)) != -1)
{
out.write(data, 0, count);
}
origin.close();
out.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
here's my full code: the cnx is established , and i am sending data to server , but i cant read anything from the server...
public class client extends Activity
{
/** Called when the activity is first created. */
Socket sock;
String spliter = "**";
String mobileNbr = "100";
String LastJOKEId = "-1";
String spliterlast = "^^$$";
BufferedReader inFromServer;
DataOutputStream outToServer;
TextView cnx;
TextView output;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupNetworking();
// Thread readerThread=new Thread(new IncomingReader());
// readerThread.start();
}
private void setupNetworking()
{
try
{
Log.i("ClientActivity", "Connecting...");
sock = new Socket("192.168.153.221", 9003);
cnx = (TextView) findViewById(R.id.textView1);
cnx.setText("Network Established.");
inFromServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
Log.i("ClientActivity", "Sending command.");
outToServer = new DataOutputStream(sock.getOutputStream());
String sentence = "logins" + spliter + mobileNbr + spliter + LastJOKEId + spliterlast;
outToServer.writeBytes(sentence + '\n');
Log.i("ClientActivity", "Sent.");
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
cnx = (TextView) findViewById(R.id.textView1);
cnx.setText("Network failed");
e.printStackTrace();
}
}
public class IncomingReader implements Runnable
{
String message;
public void run()
{
try
{
while ((message = inFromServer.readLine()) != null)
{
output = (TextView) findViewById(R.id.textView2);
output.setText(message);
}
}
catch (IOException e)
{
output = (TextView) findViewById(R.id.textView2);
output.setText("nth to display");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package some;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class NetClient {
/**
* Maximum size of buffer
*/
public static final int BUFFER_SIZE = 2048;
private Socket socket = null;
private PrintWriter out = null;
private BufferedReader in = null;
private String host = null;
private String macAddress = null;
private int port = 7999;
/**
* Constructor with Host, Port and MAC Address
* #param host
* #param port
* #param macAddress
*/
public NetClient(String host, int port, String macAddress) {
this.host = host;
this.port = port;
this.macAddress = macAddress;
}
private void connectWithServer() {
try {
if (socket == null) {
socket = new Socket(this.host, this.port);
out = new PrintWriter(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void disConnectWithServer() {
if (socket != null) {
if (socket.isConnected()) {
try {
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void sendDataWithString(String message) {
if (message != null) {
connectWithServer();
out.write(message);
out.flush();
}
}
public String receiveDataFromServer() {
try {
String message = "";
int charsRead = 0;
char[] buffer = new char[BUFFER_SIZE];
while ((charsRead = in.read(buffer)) != -1) {
message += new String(buffer).substring(0, charsRead);
}
disConnectWithServer(); // disconnect server
return message;
} catch (IOException e) {
return "Error receiving response: " + e.getMessage();
}
}
}
//---------------------------Use NetClient------------------------------------------------
NetClient nc = new NetClient(host, port, mac); //mac address maybe not for you
nc.sendDataWithString("your data");
String r = nc.receiveDataFromServer();
This is our android socket client works fine with Python server socket, Hope it will help you.
HttpResponse response = m_httpClient.execute( request );
String result = "";
if( response.getStatusLine().getStatusCode() == HttpStatus.SC_OK )
{
// open stream
InputStream stream = response.getEntity().getContent();
if( stream != null )
{
int len = 0;
byte[] buf = new byte[ 1024 ];
try
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
while( ( len = stream.read( buf ) ) > 0 )
{
outputStream.write( buf, 0, len );
}
buf = outputStream.toByteArray();
result = EncodingUtils.getAsciiString( buf );
}
catch( IOException e )
{
e.printStackTrace();
}
finally
{
stream.close();
}
}