tcp socket problem on android - android

I need to use the tcp socket connection to get the data from a bluebox, if I input a comment, such as "getcolor", the bluebox will send me the information like"red, blue".
In this case the bluebox as a server and I do not need to program on it, but I have problem to show the information on the EditText.
public class sender {
public static void main(String[] args)throws IOException{
Socket socket = new Socket("192.168.1.176",14111);
OutputStream out = socket.getOutputStream();
BufferedReader msg = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter ou = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)),true);
String buffer = new String("");
String ms = "";
while(true)
{
while(in.ready())
buffer+= in.readLine()+ "\n";
String[] line = buffer.split("\n");
while(msg.ready())
ms = msg.readLine();
if(ms.equals("exit"))
{
break;
}
if(!ms.equals(""))
{
ou.println(ms);
ou.flush();
ms = "";
}
if(!buffer.equals(""))
{
System.out.print(buffer);
buffer = "";
}
}
in.close();
out.close();
socket.close();
}
}
this java code works, but it fails in the android code below:
public class BlueBoxApp extends Activity {
/** Called when the activity is first created. */
Context appInstance = this;
private EditText info;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
info = (EditText)findViewById(R.id.EditText01);
try{
InetAddress serverAddr = InetAddress.getByName("192.168.1.176");//TCP服务器IP地址
Log.d("TCP", "server,receiving...");
Socket socket = new Socket(serverAddr,14111);
try {
OutputStream out = socket.getOutputStream();
BufferedReader msg = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter ou = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)),true);
String buffer = new String("");
String ms = "getsensorno";
Log.d("TCP", "sending:'"+ms+"'");
while(true)
{
while(in.ready())
buffer+= in.readLine()+ "\n";
while(msg.ready())
ms = msg.readLine();
if(ms.equals("exit"))
{
break;
}
if(!ms.equals(""))
{
ou.println(ms);
ou.flush();
ms = "";
}
if(!buffer.equals(""))
{
info.setText(buffer);
buffer = "";
}
}
} catch (Exception e) {
Log.e("TCP", "error",e);
}finally{
socket.close();
}
}catch(Exception e){
Log.e("TCP", "error",e);
}
}
}
what is the problem and how to set a thread for it? Thanks!

The problem, as you indicated, is that you are doing the networking part on the main thread.
Setting a new thread is easy, consider using AsyncTask. Please read the documentation (which is very good) before jumping to implement it, it will make it much easier IMHO.
Also, make sure you have internet permission in your AndroidManifest.xml

Related

How can i read string data from server ? (swift client - android server)

This is swift code (client side):
let text: String = "neslihan"
var data = NSData(data: text.dataUsingEncoding(NSASCIIStringEncoding)!)
outputStream.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
This is the android code (server side)
public class SocketServerThread extends Thread {
DataInputStream dataInputStream = null;
ServerSocket serverSocket;
public int socketServerPORT = 3671;
Socket socket = null;
#Override
public void run() {
try {
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(socketServerPORT));
while (true) {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
Log.d("messageFromClient = " , dataInputStream.readUTF());
}
}
}
There is connection but i can't see log. How can i read string data?
Use flush to commit write data
outputStream.flush()
...
while(true){
socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d("messageFromClient = " , br.readLine());
}
...

File download android server

It has been days I am struggling with this problem. I want to create a local android server to let other devices download a file in LAN. So far i have created a socket server that writes a pdf file along with header on output stream, but it is not working. When url is hit on web browser almost 95% of the data is downloaded without any problem after that download fails, it shows network problem(In Google chrome).
Following is the code to create server:
class VideoStreamServer {
public void startServer() {
outFilePath = getActivity().getExternalFilesDir("/") + "/pdf.pdf";
outFile = new File(outFilePath);
Runnable videoStreamTask = new Runnable() {
#Override
public void run() {
try {
ServerSocket socket = new ServerSocket(port);
System.out.println("Waiting for client to connect.");
while (true) {
Socket client = socket.accept();
BufferedOutputStream os = new BufferedOutputStream(client.getOutputStream());
FileInputStream in = new FileInputStream(outFile);
BufferedInputStream inFromClient = new BufferedInputStream(client.getInputStream());
StringBuilder sb = new StringBuilder();
sb.append("HTTP/1.1 200 OK\r\n");
sb.append("Accept-Ranges: bytes\r\n");
sb.append("Connection: close\r\n");
sb.append("Content-Length: " + in.available() + "\r\n");
sb.append("Content-Disposition: attachment; filename=file.pdf\r\n");
sb.append("Content-Type: application/pdf \r\n");
sb.append("\r\n");
byte[] data = new byte[1024];
int length;
//inFromClient.read(data);
//System.out.println("request from client"+getStreamData(inFromClient));
System.out.println("Thread Started");
//System.setProperty("http.keepAlive", "false");
os.write(sb.toString().getBytes());
while ((length = in.read(data)) != -1) {
os.write(data, 0, length);
}
os.close();
client.close();
socket.close();
in.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
Thread streamServer = new Thread(videoStreamTask);
streamServer.start();
}
}
Any help would be appreciated.
EDIT1
public String getStreamData(InputStream in) {
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}

How to put a timer to a TCP socket?

I need your help. I want to do this: I have a socket TCP and a Timer task in my IntentService. This is my code:
protected void onHandleIntent(Intent intent)
{
String add = intent.getStringExtra("address");
Log.d("add",add);
int porta = Integer.parseInt(intent.getStringExtra("port"));
InetAddress serverAddr = null;
try
{
serverAddr = InetAddress.getByName(add);
socket = new Socket(serverAddr, porta);
socketHandler.setSocket(socket);
final PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.print("go");
out.flush();
final byte[] bytes = new byte[1000];
int counter;
String reader;
final InputStream data = socket.getInputStream();
int numRead = 0;
if ((numRead = data.read(bytes)) >= 0)
{
reader=new String(bytes, 0, numRead);
}
if (reader.equals("Let's go"))
{
//socket connected
}
pingTimer = new Timer();
pingTimer.scheduleAtFixedRate(new TimerTask() {
String reader; int r;
public void run()
{
out.write("ping");
out.flush();
if(out.checkError())
{
onDestroy();
}
}
}, 0, 20000);
InputStream readeIn = socket.getInputStream();
char [] buffer = new char[1024];
BufferedReader in = new BufferedReader(new InputStreamReader(readeIn));
while((counter = in.read(buffer)) != -1)
{
//read here
}
catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
onDestroy();
}
}
public void onDestroy()
{
//destroy socket
}
and it works well. Now I want to do this: I want to put a timer to the socket. So, the socket is up for 3 minutes; if it receives something, re-put 3 minutes to listen, but if in these 3 minutes socket doesn't receive anything, I want to close the socket. How can I do it?
Thanks for your answers.
You need to call Socket.setSoTimeout() with an argument of 3*60*1000 which corresponds to three minutes (times 60 to give seconds, times 1000 to give milliseconds), and handle the resulting SocketTimeoutException accordingly.

Send and receive text data in background thread

I'm new in developing for Android. My app is client whith outside TCP server. I need to send text data from EditText to server in background thread with Socket. Answer from server i need to add to TextView. I see many examples, but don't see example which i could understand. So i need simple example specially for me, as that possible. Sorry for my English.
AsyncTask only for one-time using. I need only Thread. As i understand i need: Thread(Runnable), Handler, Message, Looper.. But i don't understand how use all this classes for me.
ublic class ServerWork extends Thread{
public static final Character PREFIX = ###;
public static final Character SUFFIX = ###;
public static final int SERVERPORT = ###;
public static final String SERVER_IP = ###;
private Socket socket;
String response;
String inputStr;
public ServerWork(String inputStr){
this.inputStr = inputStr;
}
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
String str = PREFIX + inputStr + SUFFIX;
PrintWriter printOut = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
BufferedReader inputBuffer = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
printOut.println(str);
printOut.flush();
char buf[] = new char[ 1000 ];
int count = inputBuffer.read( buf );
response = new String( buf, 0, count );
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Android AsyncTask send/read data using Socket

I'm working on a test project, something like a basic chat program using wi-fi connection.
I'm creating sockets to connect two different devices, but my problem is that when I send the first message, it's showing in the other device. But if I try to send again, I can see in the logs from the first one, that the message is sent, but it never shows up in the second device.
I've tried to implement the reading of the received data in another thread..or in Async Task, but the problem is still there. Here are both ways of my implementation :
Single Thread :
public void listenForSocket(){
thread = new Thread(new Runnable() {
public void run() {
Log.e("READDATAFROMSOCKET","READDATAFROMSOCKET");
try {
// sets the service running state to true so we can get it's state from other classes and functions.
serverSocket = new ServerSocket(DNSUtils.port);
client = serverSocket.accept();
client.setKeepAlive(true);
InputStream is = client.getInputStream();
Log.d("","is Size : "+is.available());
BufferedReader in = new BufferedReader(new InputStreamReader(is));
int readed = in.read();
Log.d("","readed bytes : "+readed);
String line = "";
while ((line = in.readLine()) != null) {
Log.i("","line : "+line);
changeText(line);
}
//client.close();
//serverSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
And here is AsyncTask :
class ServerTask extends AsyncTask<Void, Void, Void>{
private String line = "";
#Override
protected Void doInBackground(Void... params) {
try {
Log.e("ASYNCTASK","ASYNCTASK");
// sets the service running state to true so we can get it's state from other classes and functions.
serverSocket = new ServerSocket(DNSUtils.port);
client = serverSocket.accept();
client.setKeepAlive(true);
InputStream is = client.getInputStream();
Log.d("","is Size : "+is.available());
BufferedReader in = new BufferedReader(new InputStreamReader(is));
int readed = in.read();
Log.d("","readed bytes : "+readed);
while ((line = in.readLine()) != null) {
Log.i("","line : "+line);
}
//client.close();
//serverSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
changeText(line);
}
}
changeText(String); -
private void changeText(final String line) {
runOnUiThread(new Runnable() {
#Override
public void run() {
LinearLayout.LayoutParams params = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
TextView sendMsg = new TextView(MainActivity.this);
sendMsg.setText(DNSUtils.clientName+" : "+line);
sendMsg.setTextColor(Color.DKGRAY);
sendMsg.setTextSize(18);
layout.addView(sendMsg, params);
}
});
}
Any ideas how to fix this issue?
And another problem is that when I am reading the received data, the first letter of the sent string never shows. It always starts from the second letter.
Thanks in advance.
If i were you i will try to implement serverSocket = new ServerSocket(DNSUtils.port); only once with new; not in every thread.

Categories

Resources