i am new to android and need simple http connection codes for client server(local server in the network) communication in android application.the connection starts when the application is started and if there is any update in the server it should be notified on the client and the server response must be based on the client request.
please help.
thanks
Socket socket;
InputStream is;
OutputStream os;
String hostname;
int port;
public void connect() throws IOException {
socket = new Socket(hostname, port);
is = socket.getInputStream();
os = socket.getOutputStream();
}
public void send(String data) throws IOException {
if(socket != null && socket.isConnected()) {
os.write(data.getBytes());
os.flush();
}
}
public String read() throws IOException {
String rtn = null;
int ret;
byte buf[] = new byte[512];
while((ret = is.read(buf)) != -1) {
rtn += new String(buf, 0, ret, "UTF-8");
}
return rtn;
}
public void disconnect() throws IOException {
try {
is.close();
os.close();
socket.close();
} finally {
is = null;
os = null;
socket = null;
}
}
connect, send, read, disconnect :)
Related
I want to connect via socket to my android app.but in server side(android app) I get java.net.SocketTimeoutException error and in client side I get java.net.ConnectException: Connection refused: connecterror.
what is my mistake? thank you
server (android app)
public class ServerSocketTask extends AsyncTask<Void, Void, String> {
final StackTraceElement se = Thread.currentThread().getStackTrace()[2];
private String data = null;
#Override
protected String doInBackground(Void... params) {
Log.d(se.getClassName() + "." + se.getMethodName(), "start");
try {
ServerSocket serverSocket = new ServerSocket(8989);
serverSocket.setSoTimeout(50000);
Socket socket = serverSocket.accept();
socket.setKeepAlive(true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int readed = in.read();
Log.d("","readed bytes : "+readed);
String line;
while ((line = in.readLine()) != null){
Log.i("","line : "+ line);
}
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ServerSocketTask.this.data = result;
}
public String getData() {
return data;
}
}
client
public static void main(String[] args) {
int port;
try (Socket socket = new Socket("192.168.240.105", 8989)) {
String customerId = "123";
String requestId = Configuration.getProperty("requestId");
ClientService result = new ClientService();
String makeRequest = result.objectToJson(customerId, requestId);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.write(makeRequest);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
my client can't connect to server and my server wait for connection.
When you construct ServerSocket(8989) you're binding to wildcard address of network interfaces available on android emulator/device.
However both Android emulator and real device has it's own network interface(s) and thus it's it's own IP addresses. Your client program (development machine) IP address is not the same as IP address of android emulator/device. In other words you cannot connect to the socket created in Android app because you're using wrong address.
This answer should guide you on how to find out the address.
The code is supposed to connect as a client to a TCP server, send a command and receive a response.
The code connects and sends the command but time-out-s at "socket.getInputStream()", even though the connected server receives the command and is supposed to respond (was checked using a TCP client program on the PC).
Here Is the Code for the task:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String command;
String response = "";
MyClientTask(String addr, int port, String cmd){
dstAddress = addr;
dstPort = port;
command = cmd;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
InputStream inputStream;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(dstAddress, dstPort),2000);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(command);
inputStream = socket.getInputStream();
socket.setSoTimeout(20000);
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}catch (UnknownHostException e){
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
response = "IOException: " + e.toString();
} catch (Throwable e) {
e.printStackTrace();
response = "Throwable: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}//MyClientTask
You're reading the response until end of stream. End of stream won't occur until the peer closes the connection. You got a read timeout: ergo, probably, he didn't close the connection. Or else your timeout is too short. Two seconds isn't much.
You need a proper way of reading the response, or of dealing with the parts as they arrive.
My android app connects the server with TCP socket, to make sure the connection is ok, the server sends the "keep-alive" msg every 10s when idle, I can grab the packet in WireShark, but in my app, I can't handle the packet anywhere, seems that the packet can't be read with the socket.
Below is the code segment of my socket connection. Seems that the "keep-alive" packet just can't be read with the inputstream...
public class SocketBase {
private Socket mSocket;
private DataOutputStream out;
private DataInputStream in;
private SocketCallback callback;
private int timeOut = 1000 * 30;
public SocketBase(SocketCallback callback) {
this.callback = callback;
}
public void connect(String ip, int port) throws Exception {
mSocket = new Socket();
SocketAddress address = new InetSocketAddress(ip, port);
mSocket.connect(address, timeOut);
if (mSocket.isConnected()) {
out = new DataOutputStream(mSocket.getOutputStream());
in = new DataInputStream(mSocket.getInputStream());
callback.connected();
}
}
public void write(byte[] buffer) throws IOException {
if (out != null) {
out.write(buffer);
out.flush();
}
}
public void disconnect() {
try {
if (mSocket != null) {
if (!mSocket.isInputShutdown()) {
mSocket.shutdownInput();
}
if (!mSocket.isOutputShutdown()) {
mSocket.shutdownOutput();
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
mSocket.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
callback.disconnect();
out = null;
in = null;
mSocket = null;
}
}
public void read() throws IOException {
if (in != null) {
byte[] buffer = new byte[1024*1];
byte[] tmpBuffer;
int len = 0;
Log.i("SOCKET", "something comming");
while ((len = in.read(buffer)) > 0) {
tmpBuffer = new byte[len];
System.arraycopy(buffer, 0, tmpBuffer, 0, len);
callback.receive(tmpBuffer);
tmpBuffer = null;
}
}
}
}
The "keep-alive" packet in WireShark is like this:
If you mean a regular TCP keep-alive, there's nothing for you to detect or do. Your TCP implementation takes care of acknowledging it. There's no application data in it, so there's nothing for you to read.
I am trying to sending and receiving data between two mobile phones. Right now I can send data from one device (device 1) to another (device 2), however, when I am reading data in the same device (device 1) I am getting following error:
java.net.SocketException: Socket is closed
I am using the following code to read data:
SocketServerReadThread socketServerReadThread = new SocketServerReadThread(socket);
socketServerReadThread.run();
private class SocketServerReadThread extends Thread {
private Socket mySocket;
SocketServerReadThread(Socket socket) {
mySocket = socket;
}
#Override
public void run() {
try {
inputStream = mySocket.getInputStream();
byte[] buffer = new byte[1024];
byteArrayOutputStream = new ByteArrayOutputStream(1024);
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msgRead.setText(" Response: "+response);
}
});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
message += "Read Something wrong! " + e1.toString() + "\n";
}
}
}
I would appreciate if anyone could help me to solve the problem.
private class SocketServerReadThread extends Thread {
private Socket mySocket;
SocketServerReadThread(Socket socket) {
this.mySocket = socket;
}
BufferedReader input;
input = new BufferedReader(new InputStreamReader(
this.mySocket.getInputStream()));
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
System.out.printf("Message read is -> %s%n", read);
if (read != null) {
msgRead.setText(" Response: "+response);
}
}catch(Exception e){}}}}
I am a beginner in developing the java applications. I'm making a chat application on android. I use a thread to serve the client who comes in, but when the client has connected to the server I can not retrieve the data contained in the socket, but when a client connection is lost, data can be displayed. I use the ReadLine method to read data from the socket.
This is the program code on the server side:
package server;
import java.net.*;
import java.io.*;
import java.util.Vector;
import com.sun.org.apache.bcel.internal.generic.NEW;
public class Server {
public static void main(String[] args)throws IOException, InstantiationException,
IllegalAccessException {
ServerSocket servsocket = null;
Socket sock = null;
byte[] bytebuffer = new byte[512];
try {
System.out.println("SERVER IS RUNNING...");
servsocket = new ServerSocket(28000);
while(true){
sock = servsocket.accept();
System.out.println(servsocket.isBound());
System.out.println("Port "+servsocket+" Ready!!!");
System.out.println("Accept connection requests from " + sock);
System.out.println("From CLIENT "+sock.getInetAddress()+ " and PORT " +
sock.getPort());
ChatThread thread = new ChatThread(sock);
System.out.println("Thread is running");
thread.run();
}
} catch (IOException ioe) {
System.out.println(ioe);
}
finally{
try {
servsocket.close();
} catch (IOException ioe) {
System.out.println(ioe);
}
}
}
}
class ChatThread extends Thread{
static Vector<ChatThread> chatthread = new Vector<ChatThread>(10);
private Socket sock;
private BufferedReader in ;
private PrintWriter out;
public ChatThread (Socket socket) throws IOException {
this.sock = socket;
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(
new OutputStreamWriter(socket.getOutputStream()));
byte[] bytebuffer = new byte[512];
int receivemssg;
}
public void run(){
int recvMsgSize;
byte[] bytebuffer = new byte[512];
String readsocket;
try {
readsocket = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Below the display on the server side when the program starts. I tried to send the word "Hello ...." from the client side. Can be seen that the thread is not running.
Server is running...
true
Port ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=28000] Ready!!!
Accept connection requests fromSocket[addr=/172.17.231.254,port=3567,localport=28000]
From CLIENT /172.17.231.254 and PORT 3567
Thread is Running...
When I replace the readline method on a thread with getInputStream the thread can be run from the client and the message can be displayed. This is the code that I enter the thread to replace the readline method that I used before.
public ChatThread (Socket socket) throws IOException {
this.sock = socket;
in = sock.getInputStream();
out = sock.getOutputStream();
byte[] bytebuffer = new byte[512];
int receivemssg;
}
public void run(){
int recvMsgSize;
byte[] bytebuffer = new byte[512];
System.out.println("Thread is Running...");
String masuk = new String(bytebuffer);
System.out.println(bytebuffer);
System.out.println(in.toString());
System.out.println("thread successfully executed !!!");
synchronized (chatthread) {
chatthread.addElement(this);
}
try {
while ((recvMsgSize = in.read(bytebuffer)) != -1) {
out.write(bytebuffer, 0, recvMsgSize);
System.out.println("The length of a character is received and returned "+bytebuffer.length);
}
} catch (IOException e) {
System.out.println(e);
}
}
}
but the next problem is I can not bring up the contents of a socket in a string / text that appears is as follows:
Port ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=28000] Siap!!!
Accept connection requests fromSocket[addr=/172.17.231.254,port=3577,localport=28000]
From CLIENT /172.17.231.254 and PORT 3577
Thread is Running...
[B#7c6768
java.net.SocketInputStream#1690726
thread successfully executed !!!
The length of a character is received and returned 512
Please Help me, thanks :) GBU guys...
See the developer docmentation
public final String readLine ()
Since: API Level 1
Returns a string containing the next line of text available from this stream.
A line is made of zero or more characters followed by '\n', '\r', "\r\n"
or the end of the stream. The string does not include the newline sequence.
readLine() will block and not return until it either sees an end-of-line condition such as a newline character, or the end of the stream is reached, which is probably what happens when the connection is lost.
If you want to use readLine() you need to send "Hello....\n" or otherwise append a terminating character for readLine() to see.