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;
}
}
Related
I am not able to save data from file into an object.If I recover the data from the file and save them in a string, the application works, but as soon as I try to save them inside an object (a Note object in my case), I fail .
It is a simple app(similar to notepads) with only a mainActivity to manage operations, an object class that include two variable, one for "title" and another one for "text" and an xml file with two input fields, two buttons(load and save) and a textView to view the data.
This is the the mainActivity code:
public class MainActivity extends AppCompatActivity {
EditText title,text;
Button save,load;
TextView result;
ArrayList<Note> notes = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = findViewById(R.id.id_title);
text = findViewById((R.id.id_post));
save = findViewById(R.id.buttonSave);
load = findViewById(R.id.buttonLoad);
result = findViewById(R.id.id_result);
Context context = getApplicationContext();
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String titolo = title.getText().toString();
String post = text.getText().toString();
//Note nota = new Note(titolo,post);
Note nota = new Note(titolo,post);
//nota.setTitle(titolo);
//nota.setNote(post);
saveData(nota,context);
}
});
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//ArrayList<Note> data;
//String x;
//x= readData(context);
//x = data.getTitle() + " " +data.getNote();
//result.setText(x);
//setTextToTextview();
readData(context);
}
});
}
/**
* This function saves data on file
* #param nota
* #param context
*/
public void saveData(Note nota,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("text.txt", Context.MODE_APPEND));
outputStreamWriter.write(nota.getTitle().toString() + "," + nota.getNote().toString() + "\n");
outputStreamWriter.flush();
outputStreamWriter.close();
Toast.makeText(MainActivity.this, "Saved", Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
e.getMessage();
}
}
private void setTextToTextview() {
String text = "";
for(int i = 0; i < notes.size(); i++)
{
text = text + notes.get(i).getTitle() + "" + notes.get(i).getNote() + "\n";
}
result.setText(text);
}
/**
* Read data from file
*/
public void readData(Context context) {
String stringa = "";
String part[];
//StringBuilder stringBuilder = new StringBuilder();
try
{
InputStream inputStream = context.openFileInput("text.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ((receiveString = bufferedReader.readLine()) != null) {
StringTokenizer token = new StringTokenizer(receiveString, ",");
Note nota = new Note(token.nextToken(), token.nextToken());
notes.add(nota);
}
inputStream.close();
bufferedReader.close();
setTextToTextview();
//stringa = stringBuilder.toString();
}
}
catch (final IOException e)
{
e.printStackTrace();
}
}
/*******************************************************
*this work
*******************************************************/
/*
public String readData(Context context)
{
String ret = "";
try {
InputStream inputStream = context.openFileInput("text.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append("\n").append(receiveString);
}
inputStream.close();
bufferedReader.close();
ret = stringBuilder.toString();
}
} catch (IOException e) {
e.getMessage();
}
return ret;
}
*/
/*****************************************
* this work
*******************************************/
/*
public String readData(Context context)
{
// Note nota = new Note();
String stringa ="";
String ret = "";
try {
InputStream inputStream = context.openFileInput("text.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append("\n").append(receiveString);
ret = stringBuilder.toString();
// StringTokenizer token = new StringTokenizer(ret,",");
String split[]= ret.split(",");
for(int i = 0; i< split.length;i++)
{
stringa = stringa +"," + split[i];
}
/*
nota.setTitle(split[0]);
nota.setNote(split[1]);
notes.add(nota);
*/
/*
}
inputStream.close();
bufferedReader.close();
//setTextToTextview();
//ret = stringBuilder.toString();
}
} catch (IOException e) {
e.getMessage();
}
return stringa;
}
*/
}
I also tried like this:
public void readData(Context context) {
String stringa = "";
String part[];
//StringBuilder stringBuilder = new StringBuilder();
try
{
InputStream inputStream = context.openFileInput("text.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append("\n").append(receiveString);
stringa = stringBuilder.toString();
part = stringa.split(",",2);
Note nota = new Note(part[0],part[1]);
notes.add(nota);
setTextToTextview();
}
inputStream.close();
bufferedReader.close();
//stringa = stringBuilder.toString();
}
} catch (final IOException e) {
e.printStackTrace();
}
//return stringa;
}
thanks to anyone who can help me.
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 {
}
}
}
I have a problem. When I do a query in the stream, I have downloaded the data from the URL, everything works. But when I call AsynsTask example by pressing doInBackground() method that returns the same data, but they are updated on the URL. And they will not be updated as long as the program is restarted.
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("data.php?"+new Random().nextInt(200));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jSON_R = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return jSON_R;
}
All code
public class ParseTask extends AsyncTask<Void, Void, String> {
int intRow = 0;
String jSON_R = "";
private List<User> movieList;
Activity act;
ListView list;
LAdapter adapter;
boolean Unique = true;
public ParseTask (Activity act){
this.act = act;
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("data.php?"+new Random().nextInt(200));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jSON_R = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return jSON_R;
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
list = (ListView) act.findViewById(R.id.listVew);
Button b = (Button) act.findViewById(R.id.refresh);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//To do
}
});
movieList = new ArrayList<>();
adapter = new LAdapter(act, movieList);
list.setAdapter(adapter);
try {
JSONObject dataJsonObj = new JSONObject(strJson);
JSONArray jsa = dataJsonObj.getJSONArray("data");
for (int i = 0; i < jsa.length(); i++) {
JSONObject data1 = chat.getJSONObject(i);
String mes = data1.getString("mes1");
String mes2 = data1.getString("mes2");
String mes3 = data1.getString("mes3");
User m = new User(mes, mes2, mes3);
movieList.add(0, m);
}
adapter.notifyDataSetChanged();
intRow = jsa.length();
} catch (JSONException e) {
e.printStackTrace();
}
list.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem > 1){
Unique = false;
}else{
Unique = true;
}
}
});
Thread thread = new Thread() {
#Override
public void run() {
try {
while (true){
sleep(5000);
if (Unique){
act.runOnUiThread(new Runnable() {
#Override
public void run() {
Update();
}
});
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
private void Update(){
try {
JSONObject dataJsonObj = new JSONObject(strJson);
JSONArray jsa = dataJsonObj.getJSONArray("data");
for (int i = 0; i < jsa.length(); i++) {
JSONObject data1 = chat.getJSONObject(i);
String mes = data1.getString("mes1");
String mes2 = data1.getString("mes2");
String mes3 = data1.getString("mes3");
User m = new User(mes, mes2, mes3);
movieList.add(0, m);
}
adapter.notifyDataSetChanged();
intRow = jsa.length();
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
Calling the object in such a way
new ParseTask(getActivity()).execute();
Close the connection.
I mean use (better) reader.close() or inputStream.close()
Or try jsoup library https://jsoup.org/
i have a problem. I want to stop an httpconnection after x seconds, how can i do that? I thought something like a timertask that executes a httpconnection.close() after x seconds or something like that. Here is my code where i use my connection.
public void run() {
boolean hasCoverage = (RadioInfo.getState() == RadioInfo.STATE_ON)
&& (RadioInfo.getSignalLevel() != RadioInfo.LEVEL_NO_COVERAGE);
if (hasCoverage) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
popup = new MyPopup("Cargando Incidentes...");
UiApplication.getUiApplication().pushModalScreen(popup);
}
});
try {
HttpConnection conn = null;
String URL = "anypage.php";
conn = (HttpConnection) Connector.open(URL);
InputStream contentIn = conn.openInputStream();
byte[] data = new byte[400];
int length = 0;
StringBuffer raw = new StringBuffer();
while (-1 != (length = contentIn.read(data))) {
raw.append(new String(data, 0, length));
str = raw.toString();
}
} catch (Exception e) {
e.printStackTrace();
mainScreen.add(new RichTextField(
"Error ThreadIncidentesConnection: " + e.toString()));
}
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
String datos[] = mainScreen.split(str, "ENDOFPAGE");
// mainScreen.add(new RichTextField(""+datos[0]));
datos[0] = datos[0].substring(2, datos[0].length());
mainScreen.vecRegistro = mainScreen
.split(datos[0], "$");
mainScreen.insertoEnBd();
mainScreen.insertoEnTablaDatosBD(_act);
UiApplication.getUiApplication().popScreen(popup);
} catch (Exception e) {
e.printStackTrace();
mainScreen.add(new RichTextField(
"Error ThreadIncidentes.run: " + e.toString()));
}
}
});
} else {
mainScreen.add(new RichTextField("No hay conexión disponible."));
}
}
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();
}
}