Sign in to follow this  

Simple threaded UDP server?

This topic is 3629 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am a total noob when it comes to network programming. I am trying to setup two classes, one for the UDP server, one for the UDP client. The UDP server starts up and waits for a client to connect - as expected. But the problem is it sort of "takes over" the application, such that no other processing can be done while it is waiting for the client to connect!! I think I need to make it threaded, but I don't know what changes to make or how to do it.
 
//UDP SERVER CODE:


using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
 
namespace Robotz
{
    public class UdpSrvrClass
    {
 
        public UdpSrvrClass()
        {
            
        }
 
        public void HandleMessageReceived(object sender, EventArgs e)
        {
 
        }
 
        public void StartServer()
        {
            int recv;
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
 
            Socket newsock = new Socket(AddressFamily.InterNetwork,
                            SocketType.Dgram, ProtocolType.Udp);
 
            newsock.Bind(ipep);
            System.Diagnostics.Debug.WriteLine("Waiting for a client...");
 
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)(sender);
 
            recv = newsock.ReceiveFrom(data, ref Remote);
 
            System.Diagnostics.Debug.WriteLine("Message received from {0}:", Remote.ToString());
            System.Diagnostics.Debug.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
 
            string welcome = "Welcome to my test server";
            data = Encoding.ASCII.GetBytes(welcome);
            newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
            while (true)
            {
                data = new byte[1024];
                recv = newsock.ReceiveFrom(data, ref Remote);
 
                System.Diagnostics.Debug.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
                newsock.SendTo(data, recv, SocketFlags.None, Remote);
            }
        }
    }
}
 
 
 
 
=============================
 
 
//UDP CLIENT CODE:
 
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
 
namespace Robotz
{
    public class UdpClientClass
    {
        public event EventHandler MessageSent;
 
        private byte[] data;
        private string input, stringData;
        private UdpClient server;
 
        IPEndPoint sender;
 
            
        public UdpClientClass()
        {
        }
 
        public void ConnectToServer()
        {
            data = new byte[1024]; 
 
            server = new UdpClient("127.0.0.1", 9050);
 
            sender = new IPEndPoint(IPAddress.Any, 0);
 
            string welcome = "Hello, are you there?";
            data = Encoding.ASCII.GetBytes(welcome);
            server.Send(data, data.Length);
 
            data = server.Receive(ref sender);
 
            System.Diagnostics.Debug.WriteLine("Message received from {0}:", sender.ToString());
            stringData = Encoding.ASCII.GetString(data, 0, data.Length);
             System.Diagnostics.Debug.WriteLine(stringData);
 
            while (true)
            {
                //input = System.Diagnostics.Debug.ReadLine();
                if (input == "exit")
                    break;
 
                server.Send(Encoding.ASCII.GetBytes(input), input.Length);
                data = server.Receive(ref sender);
                stringData = Encoding.ASCII.GetString(data, 0, data.Length);
                System.Diagnostics.Debug.WriteLine(stringData);
            }
            System.Diagnostics.Debug.WriteLine("Stopping client");
            server.Close();
        }
 
        public void SendMessage(string message)
        {
            server.Send(Encoding.ASCII.GetBytes(input), input.Length);
            data = server.Receive(ref sender);
            stringData = Encoding.ASCII.GetString(data, 0, data.Length);
        }
    }
}
 
 
 
 
 
==============================
 
 
//USAGE IN THE CALLING APP:
 
 
   private void buttonStartServer_Click(object sender, EventArgs e)
        {            
            s = new UdpSrvrClass();
        
 
            s.StartServer();
        }
 
        private void buttonClientConnect_Click(object sender, EventArgs e)        
        {            
            c = new UdpClientClass();
            c.ConnectToServer();            
        }
 
        private void buttonSendMessage_Click(object sender, EventArgs e)
        {
            c.SendMessage(this.textBoxMessages.Text);
        }
 

Share this post


Link to post
Share on other sites
Quote:
I think I need to make it threaded, but I don't know what changes to make or how to do it.


If you use blocking sockets, then yes, you'll likely need to do that. Run StartServer() in a thread. Not that this will complicate things one you want to do both, send and receive, since you'll need to synchronize the data that both threads access.

Other options you have are non-blocking sockets, or asynchronous networking, but those are somewhat more complex.

Share this post


Link to post
Share on other sites
Network libraries typically have a "service()" function which the application calls each time through the main loop. Inside service(), you'll typically use select() to see which sockets are ready to receive, and then call recv() on those sockets. recv() is guaranteed to not block of select() says the socket is ready to receive.

Share this post


Link to post
Share on other sites

This topic is 3629 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this