1

How to connect server client with UDP in c# WinForms application ?

I have written a console applicaton server program but I need it as a WinForms application.

Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows;

namespace UDP_Server
{
class Program
{
    static void Main(string[] args) 
    {

        int recv;
        byte[] data = new byte[1024];
        IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 904);
        Socket newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        newSocket.Bind(endpoint);

        Console.WriteLine("Waiting for a client...");

        IPEndPoint sender = new IPEndPoint(IPAddress.Any,904);
        EndPoint tmpRemote = (EndPoint)sender;

        recv = newSocket.ReceiveFrom(data, ref tmpRemote);


        Console.Write("Message received from {0}", tmpRemote.ToString());
        Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));

        string welcome = "Sunucuya hosgeldiniz !";
        data = Encoding.ASCII.GetBytes(welcome);

        if (newSocket.Connected)
            newSocket.Send(data);

        while (true)
        {
            if (!newSocket.Connected)
            {
                Console.WriteLine("Client Disconnected.");
                //break;
            }

            data = new byte[1024];
            recv = newSocket.ReceiveFrom(data,ref tmpRemote);

            if (recv == 0)
               // break;

            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

        }

        //newSocket.Close();

    }
}
}

I need to change this code to WinForms application. How can I do that ? And also I need an client for this code.

TaW
  • 53,122
  • 8
  • 69
  • 111
alibey
  • 19
  • 5

2 Answers2

0

Please have a look at below sample projects which are built in c# form application using UDP :-

For server :-

http://www.daveoncsharp.com/2009/08/csharp-chat-application-over-asynchronous-udp-sockets-part-1/

and for Client :-

http://www.daveoncsharp.com/2009/08/csharp-chat-application-over-asynchronous-udp-sockets-part-2/

Neel
  • 11,625
  • 3
  • 43
  • 61
0

1. You have to move your code to another thread like a backgroundworker so you dont block your form (it will appear as not responding if you dont do this).

2. You shouldnt use while(true). Use an event for receiving data so you can display it when necessary.

3. To display such information on your form you have to invoke the controls, because it will be called from another Thread.

for the events you should take a look here: C# SocketAsyncEventArgs handling receive and send data

Community
  • 1
  • 1
Sebastian L
  • 838
  • 9
  • 29