Android Question Transferring Images Over A TCP/IP Socket

mre58

Member
Licensed User
Longtime User
I created a program that allows me to transfer information between my PC and my Android device over a TCP/IP socket. I want to now transfer images from my PC to my Android device also. I am not sure how I should send the files over from the PC or how to receive and save them on the Android side. I have read through a bunch of the posts in the forum, but I am still not sure how to put it together. I am not sure how to code the receiving portion on the Android side, to know how I should code it on the PC side. Any push in the right direction is appreciated.

Thank you
 

wl

Well-Known Member
Licensed User
Longtime User
Upvote 0

mre58

Member
Licensed User
Longtime User
I cannot figure out how to receive the image on my Android device. I can send an image from computer to computer, but having no luck with computer to Android. I have looked at all the examples and played around with various pieces of code, but no luck. At one point I did get the image file name to show up on the Android device, but it wasn't a valid image when I tried to open it. The code below is what I am using to send the image file from the computer to the android device.

B4X:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(String[] args)
        {
            // 1. to create a socket
            Socket sListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // 2. Fill IP
            IPAddress IP = IPAddress.Parse("192.168.1.2");
            IPEndPoint IPE = new IPEndPoint(IP, 6000);

            // 3. binding
            sListen.Bind(IPE);

            // 4. Monitor
            Console.WriteLine("Service is listening ...");
            sListen.Listen(2);

            // 5. loop to accept client connection requests
            while (true)
            {
                Socket clientSocket;
                try
                {
                    clientSocket = sListen.Accept();
                }
                catch
                {
                    throw;
                }

             
                // send the file
                byte[] buffer = ReadImageFile("c:\\images\\test.png");
                clientSocket.Send(buffer, buffer.Length, SocketFlags.None);
                Console.WriteLine("Send success!");
            }
        }

        private static byte[] ReadImageFile(String img)
        {
            FileInfo fileInfo = new FileInfo(img);
            byte[] buf = new byte[fileInfo.Length];
            FileStream fs = new FileStream(img, FileMode.Open, FileAccess.Read);
            fs.Read(buf, 0, buf.Length);
            fs.Close();
            //fileInfo.Delete ();
            GC.ReRegisterForFinalize(fileInfo);
            GC.ReRegisterForFinalize(fs);
            return buf;
        }

    }
}

Thank you
 
Upvote 0

mre58

Member
Licensed User
Longtime User
The code below is what I am using on the Android side. I get the file, but it isn't a valid image file so I can't open it.

B4X:
Sub Process_Globals
    Dim Socket1 As Socket
  Dim AStreams As AsyncStreams
  Dim Bitmap1 As Bitmap
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
    Socket1.Initialize("Socket1")
    Socket1.Connect("192.168.1.2" , 6000, 20000)
End Sub

Sub Socket1_Connected (Successful As Boolean)
    If (Successful) Then
      AStreams.Initialize(Socket1.InputStream, Socket1.OutputStream,"AStreams")
      ToastMessageShow("connected",False)
  Else
      Msgbox(LastException.Message, "Error connecting")
      Socket1.Close
      Activity.Finish
    End If
End Sub

Sub AStreams_NewData (Buffer() As Byte)
  '  Dim msg As String
  '  msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    Dim out As OutputStream
    out = File.OpenOutput(File.DirRootExternal, "newimage.png", False)
    out.WriteBytes(Buffer, 0, Buffer.Length)
    out.Close
  ' Msgbox("Time received: " & CRLF & msg, "")
    Socket1.Close
  Activity.Finish
End Sub
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
You cannot assume that the whole file will be sent as a single "packet". This is why I suggested that you first send the file size. You should read the file size and then append the buffer to the file until you reach the correct size.

See the prefix section in the tutorial: http://www.b4x.com/android/forum/threads/asyncstreams-tutorial.7669/#content

You can also check B4A-Bridge source code.
 
Upvote 0

tango

Member
Licensed User
Longtime User
hi erel, how can i do the test of tcp/ip in services module.
app stopped every time. my code is

'SERVİCE MODULE

Sub Process_Globals
Private TimerService As Timer
Dim Counter,kayitsayisi As Int
Counter=0
Dim Timer1 As Timer
Dim connected As Boolean
Dim AStreams As AsyncStreams
Dim i,j,kayitsayisi As Int
Dim msg As String

End Sub

Sub Service_Create
TimerService.Initialize("TimerService",10000)
TimerService.Enabled=True
i=0
j=0
StartServiceAt("",DateTime.Now,False)
End Sub

Sub Service_Start
j=j+1
End Sub

Sub TimerService_Tick
i=i+1
msg=i
Dim socket1 As Socket
socket1.Initialize("Socket1")
socket1.Connect("192.168.2.63",3306,5000)
If socket1.Connected=True Then
StartServiceAt("",DateTime.Now,False)
End If
End Sub
 
Upvote 0
Top