C# UDP Server - Keep-Alive Packets

2019-09-04 10:41发布

I'm currently making a small application in C# with a client/server architecture, that uses the UDP protocol. This is a code that'll be eventually used in a 2D game which will be made in Windows Forms Application.

Now, since UDP is connectionless, I made it so when a user connects, he sends his name to the server in a specialized message, and when the server receives the join message, he adds the client to a string list.

Now, the problem is, I don't know how to make a disconnection of the client.

Of course, I can make it so if the client clicks a Disconnect button, it sends a message to the server to disconnect him.

But what if he just exits the application by clicking 'X', or his power runs out?

I thought about making Keep-Alive packets, but I couldn't think of an effective way to do so.

Here's the server code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace UDP_Server
{
    class Program
    {
        Socket _serverSocket;
        List<string> clients;
        static void Main(string[] args)
        {
            Program go = new Program();
            go.Server();
        }
        void Server()
        {
            byte[] msg = new byte[1024];
            _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 12345));
            while (true)
            {
                IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint Remote = (EndPoint)(sender);
                int recv = _serverSocket.ReceiveFrom(msg, ref Remote);
                string data = Encoding.ASCII.GetString(msg);
                if (data.Contains("Name!"))
                {
                    clients.Add(data.Split('!')[1]);
                }
                else Console.WriteLine("Message received from {0}:", Remote.ToString());
                Console.WriteLine(Encoding.ASCII.GetString(msg));
                //_serverSocket.SendTo(msg, Remote);
            }
        }
    }
}

There's no need for the client code, since the only thing its doing is using the SendTo method to send a datagram to the server, and a receive method to get data.

So how can I make a keep-alive architecture? Also, if I make it for more than ore person, should I use multithreading?

1条回答
等我变得足够好
2楼-- · 2019-09-04 11:00

I can't answer your specific question, but would WCF be an option?

I'm not sure what your application is for specifically, but WCF takes away a lot of the headaches in connections"ful" and connection"less" scenarios.

WCF clients can connect and disconnect and the server is capable of handling multiple users, even with or without "multithreading", as you say. Hope this helps.

查看更多
登录 后发表回答