UTF-8 chars reading in Android socket connection - android

I've prepared socket client connection like this:
Socket socket = new Socket();
socket.setSoTimeout(500);
hostname = "XX.YY.ZZ.XX";
socket.connect(new InetSocketAddress(hostname, port), 6000);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
false);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
and I read data using i.e. this code:
if (in.ready() == true) {
String message = in.readLine();
Log.e("MyApplication", "data=" + message);
}
When I look in logcat I see ? char instead of every national characters.
I'm sure data sending to my android application is in utf-8 charset therefore I tried to use code like this:
UTF8Str = new String(message.getBytes(),"UTF-8");
or creating BufferReader like this:
in = new BufferedReader(new InputStreamReader(
socket.getInputStream(),"UTF-8"));
but everything without success.
Can somebody help me resolve problem conversion chars to display them in logcat as nationals (my main goal is to display them in TextView). Everything worked two weeks ago but after some Ecclipse reconfiguration (I can't back to old settings) stoped.
~Artik

Related

Socket input stream and Unicode

I try to write an app that sends text from Windows computer to Android cellphone.
The text I send can be in English or Hebrew (for example). The connection is via Socket. The code I use on the Windows side (Visual studio 2012):
String buffer = // Some text
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(buffer + "\n");
// Send the data through the socket.
int bytesSent = socketSender.Send(msg);
And on the Android side:
//After I establish the Socket
String text = "";
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isr);
while ((inputText = in.readLine()) != null)
{
text = inputText;
}
All this works perfectly when sending English text.
When I try to send Hebrew text I replace to this line:
byte[] msg = Encoding.Unicode.GetBytes(buffer + "\n");
But on the Android side I can't "read" it.
I tried to use CharsetEncoder but didn't work (or I did it the wrong way).
Any ideas?
Ok, so the answer is:
on the Windows side:
byte[] msg = Encoding.UTF8.GetBytes(buffer + "\n");
And on the Android side:
InputStreamReader isr = new InputStreamReader(is, "UTF-8");

Receive string in socket programming android

I am working on client server android application here my client is my application . I am sending string to server through wireless router . Sending of string is working fine but I am not getting how to deal with response string from server.
here is my code for sending and receiving strings
for sending
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Try this
InputStream is=socket.getInputStream();
int ch;
StringBuffer sb=new StringBuffer();
while((ch=(is.read))!=-1)
{
byte b=(byte)ch;
sb.append(b);
}
String response=sb.toString();

How to read a socket command sent by VB.NET to Android?

I'm trying to send some commands to Android (client) from VB.NET (server) using sockets. I can connect the client to the server, but I don't know how to receive the commands sent by the server.
Here's a part of my Android code:
public void connect(View v){ //called on button click
SERVER_IP = ip.getText().toString(); //it gets the server's ip from an editText
SERVER_PORT = Integer.parseInt(port.getText().toString()); //and the port too
Toast.makeText(this, "Trying to connect to\n" + SERVER_IP + ":" + SERVER_PORT + "...", Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
public void run() {
InetAddress serverAddr;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVER_PORT); //It establishes the connection with the server
if(socket != null && socket.isConnected()){ //not sure if it is correct
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//Here comes the problem, I don't know what to add...
}
} catch (Exception e) {
}
}
}).start();
}
And here's a part of my VB.NET send code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
send(TextBox1.text)
End Sub
Private Sub Send(ByVal command)
Dim temp() As Byte = UTF8.GetBytes(command) 'Is UTF8 right to use for that?
stream.Write(temp, 0, temp.Length)
stream.Flush()
End Sub
Question1: is it right to us UTF8 instead of for example ASCII encoding?
Question2: what would I change in the Android code if it wanted to use a timer that sends a command every second?
Thanks.
To read input from a BufferedReader you need to do something similiar to this:
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while((line = input.readLine()) != null){
// do something with the input here
}
A nice tutorial on sockets is available from oracle in the docs: http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
The default charset on Android is UTF-8 http://developer.android.com/reference/java/nio/charset/Charset.html, so no worries there but you can always send a byte stream from the server onto the client and decode it however you want.
To receive a byte stream you need to do this:
BufferedInputStream input = new BufferedInputStream(socket.getInputStream());
byte[] buffer = new byte[byteCount];
while(input.read(buffer, 0, byteCount) != -1 ){
// do something with the bytes
// for example decode it to string
String decoded = new String(buffer, Charset.forName("UTF-8"));
// keep in mind this string might not be a complete command it's just a decoded byteCount number of bytes
}
As you see it's much easier if you send strings instead of bytes.
If you want to receive input from the server periodically, one of the solutions would be to create a loop which opens a socket, receives input, process it, closes the socket, and then repeats, our you could just keep the loop running endlessly until some command like "STOP" is received.

TcpSockets android: How to return from bufferreader.readline without server response

Below code is implemented in AsynTask and with try-catch. I want to interrupt bufferreader.readline() if server does not respond with in Specified time. How can I achieve this?
Socket tcpSocket = new Socket();
tcpSocket.connect(new InetSocketAddress("mydomain.com", 5000),
SOCK_TIMEOUT);
InputStream inputStream = tcpSocket.getInputStream();
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(inputStream));
String jsonData = bufferReader.readLine(); //blocks here
Simply close the socket and it will return with socket exception.

Socket connection getting closed while reading data from socket

I am writting simple program to connect server by socket in android.
But when i try to read data from socket's outputstream it will send automatically RST request. so my connection gets closed. but i want my connection to open always.
Please any one help me.
Thank you.
try {
Socket socket = new Socket("xxx.xxx.x.xx", 9083);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println("Testing");
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String readObject = reader.readLine();
System.out.println(readObject);
} catch (Exception e) {
e.printStackTrace();
}
The most usual reason for 'connection reset' is that you have written to a connection that has already been closed by the other end. In other words, an application protocol error.

Categories

Resources