Danial
Danial

Reputation: 451

Send and Receive TCP socket android client

I wrote c# client-server application, server is sending data using socket.send(byte[]) and receive using socket.receive(byte[]) now i want to send and receive from android and totally new to android.

i appreciate any kind of help.

Upvotes: 2

Views: 6050

Answers (2)

Brian Coleman
Brian Coleman

Reputation: 1070

You can use a TCP socket and a input stream to read data in a separate thread from the main application thread in your android app like this:

// Start a thread
new Thread(new Runnable() {
 @Override
 public void run() {
 // Open a socket to the server
 Socket socket = new Socket("192.168.1.1", 80);
 // Get the stream from which to read data from
 // the server
 InputStream is = socket.getInputStream();
 // Buffer the input stream
 BufferedInputStream bis = new BufferedInputStream(is);
 // Create a buffer in which to store the data
 byte[] buffer = new byte[1024];
 // Read in 8 bytes into the first 8 bytes in buffer
 int countBytesRead = bis.read(buffer, 0, 8);
 // Do something with the data

 // Get the output stream from the socket to write data back to the server
 OutputStream os = socket.getOutputStream();
 BufferedOutputStream bos = new BufferedOutputStream(os);
 // Write the same 8 bytes at the beginning of the buffer back to the server
 bos.write(buffer, 0, 8);
 // Flush the data in the socket to the server
 bos.flush();
 // Close the socket
 socket.close();
}
});

You can wrap the input stream in various other types of stream if you want to read in multibyte values such as shorts or ints (DataInputStream). These will take care of converting from network endianess to the native endianess of the client.

You can get an output stream from the socket to write data back to the server.

Hope this helps.

Upvotes: 1

mohamed sakr
mohamed sakr

Reputation: 116

//client side        
        Socket sendChannel=new Socket("localhost", 12345);
        OutputStream writer=sendChannel.getOutputStream();
        writer.write(new byte[]{1});
        writer.flush();

        InputStream reader=sendChannel.getInputStream();
        byte array[]=new byte[1];
        int i=reader.read(array);

//server side
        ServerSocket s=new ServerSocket(12345);
        Socket receiveChannel = s.accept();

        OutputStream writerServer=receiveChannel.getOutputStream();
        writer.write(new byte[]{1});
        writer.flush();

        InputStream readerServer=receiveChannel.getInputStream();
        byte array2[]=new byte[1];
        int i2=reader.read(array);

Upvotes: 3

Related Questions