Share via


Socket over usb-port

Question

Monday, May 17, 2010 12:05 PM

Hi,

I would like to write sockets on client  to send  and receive Streamdata throught USB-port.

My client is a mobile device windows ce and my server is java.

will be a problem that the connecition is over usb-ports?

I wrote this code, what is missing to read a message?

 private void button1_Click(object sender, EventArgs e)
    {

     string data;

     IPEndPoint ip = new IPEndPoint(IPAddress.Any, 666);

     Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

     try
     {
       server.Connect(ip);
     } catch (SocketException se)
     {
       Console.WriteLine(se.ToString());
       return;
     }

     NetworkStream ns = new NetworkStream(server);
     StreamReader sr = new StreamReader(ns);
    // StreamWriter sw = new StreamWriter(ns);

     data = sr.ReadLine();
     MessageBox.Show(data);

     sr.Close();
     // sw.Close();
     ns.Close();
     server.Shutdown(SocketShutdown.Both);
     server.Close();
    }

All replies (2)

Monday, May 17, 2010 12:52 PM ✅Answered

a library to talk with the usb can be found @ http://sourceforge.net/projects/libusbdotnet/

here is the .Net class for talking with serial ports http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx

also another post with almost same question http://social.msdn.microsoft.com/forums/en-US/winforms/thread/8b1f79cb-d9e7-4797-9b9e-e15cf4d9b78b

Mahmoud Darwish Senior Software Developer C#/VB


Monday, May 17, 2010 8:05 PM ✅Answered

In standard .NET framework (in my humble opinion) this USB connection is not possible. You should hang to other parties addons as the collegue suggested, or try another more standard way.

For the code:

instead of a .Connect, you can add a server.Bind(new IPEndPoint(IPAddress.Any, 666); and a server.Listen();

then you have to receive chunks of data until the client closes the connection, and this is indicated by a 0 return, so:

Socket client = server.Accept();
byte[] rcvBuffer = new byte[1000]; //or your preferred buffer size
Int32 bytesReceived = 0;
Int32 totalBytesReceived = 0;
while ((bytesReceived = client.Receive(rcvBuffer, 0, rcvBuffer.Lenght, SocketFlags.None))>0)
         { totalBytesReceived += bytesReceived; }
client.Close();

Something like this would make the job.

Giuseppe