none
C# socket programming file transfer UDP RRS feed

  • Question

  • Hi there, I tried to modify this

    http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/67935373-6b11-4112-8803-6aa76e077c46?persist=True

    to make it run on an UDP port , but I didnt manage to do so.

    Can anyone help me? What do I need to change besides

    Socket clientsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); to

    Socket clientsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp;

    I hope that you can help me, it's pretty urgent :(

    Saturday, May 11, 2013 2:20 PM

Answers

  • See answers below

    1) But don't understand what the server ip adress might be. I try to do in localhost.

    Answer : Right click on Mycomputer on server and select properties.  The 2nd tab is Computer name.   Use this name in th eclient. to make sure client can see the server open a cmd.exe window.  Then type "Ping ServerName" and replace the server name with the one found in MyComputer properties on the server.

    2) Then  clientsocket.Connect("Server IP or Name", portnumber (int)); same question, and what port? can i use any?

    Answer : The port number in client and server must be the same and not one used by other applications.  You want to use a port that isn't going to be blocked by any firewall so I usually recommend a port number above 10,000 like 12354

    3) Then i see that in server code i dont need to change anything?

    The code right here

    server.Listen(10); need to be used in udp?

    Answer : Yes you should change the port number from 10

    4) I think I know that in a udp connection you dont need to listen? Am I wrong?

    Wrong.  You always have a socket.  Your VS application will make a connection to a socket.  The socket can on your local PC or on a remote PC.  The socket class also have a number of inherited application classes like Client and Listener.  Here are some of the different ways of using a socket class

    1) Broadcast - server sends out messages on a port number without a connection from a client.  Client listens for port number.  All other cases yu require a connection.

    2) Non Broadcast (either UDP or TCP)

          Server starts first and can either use a Socket Class, Client Class (inherits Socket class), or Listen Class (inherits Client class).   The only differences is the Client and Listener in the constructor sets up more of the default properties, and the hides some of the socket methods.  You can look at client and Listener as specialized sockets.

         Client  is the same as server but you don't use the listener.

           Just remember the Server always connects to a local IP address on the PC where it is running.  The client always connects to the server PC (except for Broadcast).  The client always must connect to a real IP address (not loopback 127.0.0.1 except for Broadcast) ) or computer name.  The server can connect to either to a real IP address or loopback address.  The ethernet driver on the PC will forward any IP messages from the Real IP to the loopback if the port number is the same.


    jdweng

    Sunday, May 12, 2013 12:45 PM

All replies

  • I'm assuming that you are trying to send regular UDP and not Multicast.  YouIP address may be wrong so let me explain what they should be

    Make sure you start the server first.

    1) client code  - IP address should be the server IP address

     IPAddress[] ipAddress = Dns.GetHostAddresses("127.0.0.1")  <---this is wrong. It should be the server IP address.  127.0.0.1 is the loopback address which is on the client (not server)

    IPEndPoint ipEnd = new   
    IPEndPoint(ipAddress[0], 5656);
        Socket clientsocket = new
    Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

    Note : endpoint not needed you can make this change instead

    from : clientsocket.Connect(ipEnd);

    to :  clientsocket.Connect("Server IP or Name", portnumber (int));

    2) Server - Note : IPAddress is the loopback address 127.0.0.1

        IPEndPoint ipEnd = new
    IPEndPoint(IPAddress.Any, 5656);
        Socket server = new
    Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

    The server should start first and listen for a connection on the loopback address.  The client needs to connect to the server IP address to complete the connection.

    You can can enter the following on a cmd.exe window to check the connection status.

    netstat -a

    Do this on both client and server.  Look for the port number that you are using.  When you start the server first you will see the port number being opened.  Then after the client connects you will see the status as being connected.


    jdweng


    Saturday, May 11, 2013 5:17 PM
  • Thank you for your response.

    But don't understand what the server ip adress might be. I try to do in localhost.

    Then  clientsocket.Connect("Server IP or Name", portnumber (int)); same question, and what port? can i use any?

    Then i see that in server code i dont need to change anything?

    The code right here

    server.Listen(10); need to be used in udp? I think I know that in a udp connection you dont need to listen? Am I wrong?

    Here is the code again

    public class ServerS
    {
        

        //static string  fileName = "emailsample.zip";
        //static  string filePath = @"E:\";

        static void  Main(string[] args)
        {

          try
          {
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            server.Bind(ipEnd);
            server.Listen(10);

            Console.WriteLine("Waiting for client...");
            Socket serverSocket = server.Accept();
            
            byte[] data = new byte[1024 * 5000];
            int received = serverSocket.Receive(data);
            int fileNameLen = BitConverter.ToInt32(data, 0);
            string fileName = Encoding.ASCII.GetString(data, 4, fileNameLen);
            //BinaryWriter bWrite = new BinaryWriter(File.Open(fileName, FileMode.Create, FileAccess.Write));
            BinaryWriter bWrite = new BinaryWriter(File.Create(@"D:\a.txt"));
            bWrite.Write(data, fileNameLen + 4, received - fileNameLen - 4);
            int received2 = serverSocket.Receive(data);
          while (received2 > 0)
            {
              bWrite.Write(data, 0, received2);
              received2 = serverSocket.Receive(data);
            }
            bWrite.Close();
            serverSocket.Close();
          }
          catch (Exception ex)
          {
            Console.WriteLine("Error sending file." + ex.Message.ToString());
          }
          Console.Write("press a key");
          Console.ReadKey();
        }
      }

    class ClientS
        {

            static void Main(string[] args)
            {

                string filenametouse = @"c:\a.txt";
                try
                {

                    IPAddress[] ipAddress = Dns.GetHostAddresses("");
                    IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
                    Socket clientsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

                    byte[] filenamedata = Encoding.ASCII.GetBytes(filenametouse);
                    byte[] output = new byte[4 + filenamedata.Length];
                    BitConverter.GetBytes(filenamedata.Length).CopyTo(output, 0);
                    filenamedata.CopyTo(output, 4);
                    //clientsocket.Connect(ipEnd);
                     clientsocket.Connect("",);
                    Console.WriteLine("Connected..");
                    clientsocket.SendFile(filenametouse, output, null, TransmitFileOptions.UseDefaultWorkerThread);
                    Console.WriteLine("File : {0} sent.", filenametouse);

                    clientsocket.Close();

                }
                catch (Exception ex)
                {
                    Console.WriteLine("File receiving error :" + ex.Message.ToString());
                }

                Console.WriteLine("Press a key");
                Console.ReadKey();
            }

        }
    }


    And i've set multiple startup project in Visual Studio to do what you've told me.
    Sunday, May 12, 2013 11:01 AM
  • See answers below

    1) But don't understand what the server ip adress might be. I try to do in localhost.

    Answer : Right click on Mycomputer on server and select properties.  The 2nd tab is Computer name.   Use this name in th eclient. to make sure client can see the server open a cmd.exe window.  Then type "Ping ServerName" and replace the server name with the one found in MyComputer properties on the server.

    2) Then  clientsocket.Connect("Server IP or Name", portnumber (int)); same question, and what port? can i use any?

    Answer : The port number in client and server must be the same and not one used by other applications.  You want to use a port that isn't going to be blocked by any firewall so I usually recommend a port number above 10,000 like 12354

    3) Then i see that in server code i dont need to change anything?

    The code right here

    server.Listen(10); need to be used in udp?

    Answer : Yes you should change the port number from 10

    4) I think I know that in a udp connection you dont need to listen? Am I wrong?

    Wrong.  You always have a socket.  Your VS application will make a connection to a socket.  The socket can on your local PC or on a remote PC.  The socket class also have a number of inherited application classes like Client and Listener.  Here are some of the different ways of using a socket class

    1) Broadcast - server sends out messages on a port number without a connection from a client.  Client listens for port number.  All other cases yu require a connection.

    2) Non Broadcast (either UDP or TCP)

          Server starts first and can either use a Socket Class, Client Class (inherits Socket class), or Listen Class (inherits Client class).   The only differences is the Client and Listener in the constructor sets up more of the default properties, and the hides some of the socket methods.  You can look at client and Listener as specialized sockets.

         Client  is the same as server but you don't use the listener.

           Just remember the Server always connects to a local IP address on the PC where it is running.  The client always connects to the server PC (except for Broadcast).  The client always must connect to a real IP address (not loopback 127.0.0.1 except for Broadcast) ) or computer name.  The server can connect to either to a real IP address or loopback address.  The ethernet driver on the PC will forward any IP messages from the Real IP to the loopback if the port number is the same.


    jdweng

    Sunday, May 12, 2013 12:45 PM