Click here to Skip to main content
Click here to Skip to main content

Genesis UDP Server and Client

By , 21 Dec 2005
 

Sample Image

Introduction

The Genesis UDP project is a class library that implements a lightweight UDP server and client using the .NET sockets functionality. It uses UDP to keep the amount of data being sent across the network low, and has many features such as basic encryption, sequenced packets, and a reliable channel.

Genesis communicates via "command packets" - a command packet is one or more UDP packets that have a 2 byte opcode, and a variable number of string fields. Unreliable packets can be up to 512 bytes, reliable packets can be longer but are split up by Genesis and sent in sequence. There are a few internal opcodes used by Genesis, but apart form that, how packets, opcodes and fields are handled is totally the responsibility of the host application developer.

There is also an optional encryption system, it is not too advanced but if enabled, will generate a random 320 bit key for each connecting client and use that key in an XOR encryption algorithm. This is quite secure as no two clients share the same key, however it relies on the initial connection packets not being sniffed. Adding public/private key encryption etc. is a possible enhancement to the library. It is possible to be selective over which connections are encrypted and which are not.

Servers vs. Clients

Genesis works on the basis that every instance of Genesis can be both a client and a server. The line between the client and the server is blurred, as any application that uses Genesis can both connect to servers and accept connections from clients. Of course, clients can't just connect by default - the appropriate events must be hooked in the host application to enable the functionality. A server is defined as the remote host that accepted the connection, whilst a client is the remote host that initiated the connection. As an instance of Genesis can do both, it can be both a server and client to other Genesis instances. Servers and clients are known collectively simply as hosts.

The diagram above shows how the idea of clients and servers works in Genesis. Each blue box represents an instance of the Genesis library - none are specifically designated servers or clients as both can potentially accept and initiate connections. The definition of server and client is only valid in the context of a single Genesis instance. Let us consider "Genesis 1", it is connected to servers 2 and 3, and 4 is connected as a client, this is determined by the directions of the arrows (the arrows represent which box initiated the connection). If we look at the perspective of "Genesis 2", we see there are just two clients, 1 and 3. However, if we look at the perspective of "Genesis 4", there is one server, "Genesis 1". Notice how "Genesis 1" can be both a client or server depending upon the context.

Background

The idea for Genesis was based on looking at the network protocols of the various online FPS games such as Quake and Half-Life, which use UDP to allow fast communication between the game server and its connected clients. These implementations have the option to send reliable and sequenced packets - abilities which are also incorporated into Genesis. The original intention for Genesis was to be the start of an underlying network API for a game engine written in .NET, however its potential is so great it has been given to the community as a standalone project.

Using the code

There are three interfaces that must be used to implement the Genesis functionality. These are:

  • IConnection
  • ICommand
  • IGenesisUDP

The IConnection objects hold information about each connection to a remote host, whether that host is a server or a client. ICommand holds information about a single command packet, including the opcode and data fields. IGenesisUDP is the actual communications class that controls all of the functionality.

Included with the source are two projects "GenesisChatServer" and "GenesisChatClient". These are a pair of projects that implement a chat system similar to IRC. Using these projects as a reference point should help with understanding the Genesis classes.

Creating A Server

Let's look at the GenesisChatServer - this project shows how Genesis can act as a server to serve other instances of Genesis (the clients).

First, we need to declare and instantiate the Genesis object in the host application.

private GenesisCore.IGenesisUDP m_UDP;

... 

m_UDP = GenesisCore.InterfaceFactory.CreateGenesisUDP("ChatServer");

Notice how the class InterfaceFactory was used to create an instance of Genesis.

The GetLocalAddresses method is used to return a list of local IP addresses on the current machine - and is used to populate a combo box in the chat server application.

string[] addresses = m_UDP.GetLocalAddresses( );
...

In order to handle the Genesis communication events, they must be hooked as per the code below:

//Hook genesis core events
m_UDP.OnListenStateChanged += new ListenHandler(m_UDP_OnListenStateChanged);
m_UDP.OnConnectionAuth += new ConnectionAuthHandler(m_UDP_OnConnectionAuth);
m_UDP.OnCommandReceived += new IncomingCommandHandler(m_UDP_OnCommandReceived);
m_UDP.OnConnectionStateChanged += new 
   ConnectionStateChangeHandler(m_UDP_OnConnectionStateChanged);

OnListenStateChanged is called when the state of the Genesis communication changes, it can be in one of two states: "Listen" or "Closed", which is just effectively like enabling or disabling the communication. When Closed, Genesis will drop all remote connections and close the socket.

OnConnectionAuth is called when a client has sent authorization information - this is where the client can be rejected if, for example, the logon credentials are not accepted. In the chat server example, the connection is rejected if the nickname is too short or if the server password is incorrect. Notice how a rejection reason can be sent back to the client. Everything is controlled by modifying the ConnectionAuthEventArgs object sent with the event. The command containing the authorization information can be accessed by the AuthCommand property of the event arguments.

private void OnConnectionAuth(object o, ConnectionAuthEventArgs e)
{
    ... 
 
    if(e.AuthCommand.Fields[1].Length < 3)
      {
        e.AllowConnection = false;
        e.DisallowReason = "Nickname too short.";
        return;
      }
      else if(e.AuthCommand.Fields[1].Length > 15)
      {
        e.AllowConnection = false;
        e.DisallowReason = "Nickname too long.";
        return;
        }

    ...
 }

OnCommandRecieved is called when a remote host sends a command to Genesis. The eventargs for this event allows access to the ICommand object interface (via the SentCommand property) that contains the information relating to the command sent, and allows access to the data fields and opcode. There is also the ability to get the object corresponding to the remote host that sent the command (via the Sender property). This event is only fired from authorized hosts. The chat server uses this event to handle incoming chat messages and user list requests.

OnConnectionStateChanged is fired when a remote host connects or disconnects from the Genesis instance. The eventargs contain information regarding the host, whether it connected or disconnected, and a disconnection reason if the latter. The chat server uses this event to send a connected user list to the newly connected clients.

Creating A Client

Let's look now at the client side of the chat project, "GenesisChatClient". This is similar to the server application in that it instantiates an instance of Genesis and hooks up various events, however some new events are hooked:

m_UDP.OnListenStateChanged += new ListenHandler(m_UDP_OnListenStateChanged);
m_UDP.OnLoginRequested += new SendLoginHandler(m_UDP_OnLoginRequested);
m_UDP.OnAuthFeedback += new AuthenticatedHandler(m_UDP_OnAuthFeedback);
m_UDP.OnConnectionStateChanged += new 
  ConnectionStateChangeHandler(m_UDP_OnConnectionStateChanged);
m_UDP.OnCommandReceived += new IncomingCommandHandler(m_UDP_OnCommandReceived);
m_UDP.OnConnectionAuth += new ConnectionAuthHandler(m_UDP_OnConnectionAuth);
m_UDP.OnSocketError += new SocketErrorHandler(m_UDP_OnSocketError);
m_UDP.OnConnectionRequestTimedOut += new 
  RequestTimedOutHandler(m_UDP_OnConnectionRequestTimedOut);

OnLoginRequested is triggered when the server requests the login details from the client. The client must send a command packet back to the server with the opcode OPCODE_LOGINDETAILS and the appropriate data fields. In the chat sample, this packet contains the user's nickname and the server password:

private void OnLoginRequested(object o, LoginSendEventArgs e)
{
    if(e.Connected)
    {
        e.ServerConnection.SendUnreliableCommand(0, 
               GenesisConsts.OPCODE_LOGINDETAILS, 
               new string[] {txtServerPW.Text, txtNickName.Text} );
        spState.Text = "Sending login details...";
    }
    else
    {
        spState.Text = "Connection rejected - " + e.Reason;
    }
}

The Connected property of the LoginSendEventArgs object is false if the server is unable to accept the connection, for example, if it has reached the maximum capacity. The reason for the rejection is also accessible if needed, in the Reason property.

OnAuthFeedback is triggered when the server has made a decision on whether or not to accept the connection. The eventargs contains a value that determines whether the auth succeeded, and the reason for the failure if otherwise.

OnConnectionAuth is fired when a remote host tries to connect to Genesis, remember this is used in the chat server for authenticating remote hosts. The chat client can accept no connections (as it is acting as a client), so a small piece of code is entered here to reject the connection and send a rejection reason back. If the event was not hooked at all by the client application, the connection would still be rejected, but no reason would be sent to the host attempting to connect.

private void m_UDP_OnConnectionAuth(object o, ConnectionAuthEventArgs e)
{
    //Clients don't accept connections.
    e.AllowConnection = false;
    e.DisallowReason = "Can't connect directly to a chat client";
}

One thing of importance is how connections are established from the client. It starts in the chat client with the following code:

/// <summary>
/// Connect to server button was clicked
/// </summary>
private void btnConnect_Click(object sender, System.EventArgs e)
{
    server_ip = txtServerIP.Text;
    m_UDP.RequestConnect(ref server_ip, 
       Convert.ToInt32(txtServerPort.Text), 
       out server_req_id);
    spState.Text = "Connecting...";
    btnConnect.Enabled = true;
}

The RequestConnect method handles initiating the connection. Notice that the server IP parameter is by reference; this is because it is possible to pass the method a host name (rather than an IP address), but the IP will be resolved and the actual string will be changed to the IP address. This allows the host application to take advantage of the hostname resolution, and is required when using other functions within Genesis (as many of the connection search functions will only accept the remote host IP address). The other parameter to note is the last parameter, which is an out parameter and returns the connection request ID. This ID is a number unique to all connection requests and allows a connection request to be cancelled via the CancelConnect method.

Note that establishing a connection is an asynchronous operation, and to catch whether a connection has succeeded requires the use of two events, OnConnectionRequestTimedOut and OnConnectionStateChanged. If the connection attempt times out, the former event is fired. If the connection attempt succeeds, then the latter is fired with arguments that show a connection has been established. Both of these events allow access to the remote host address and the connection request ID generated at the call to RequestConnect to allow differentiation between different connections and connection requests. This can be seen implemented in the GenesisChatClient project.

Sending Data to Remote Hosts

Genesis wraps this functionality in very easy to use method. Two of the methods reside in the IConnection object, these are shown below:

int SendUnreliableCommand(byte flags, string opcode, string[] fields);
int SendReliableCommand(byte flags, string opcode, string[] fields);

These two methods allow sending a single command packet to the remote host associated with the IConnection object. The opcode and fields can be any data the host application recognizes, valid values for the flags are given below (from Constants.cs):

//Command packet flags
public static byte FLAGS_NONE = 0;
public static byte FLAGS_CONNECTIONLESS = 1;
public static byte FLAGS_ENCRYPTED = 2;
public static byte FLAGS_COMPOUNDPIECE = 4;
public static byte FLAGS_COMPOUNDEND = 8;
public static byte FLAGS_RELIABLE = 16;
public static byte FLAGS_SEQUENCED = 32;

Of the flags available in the Constants.cs file, only one should ever be used manually in the method calls, and that is FLAGS_SEQUENCED which applies a sequencing to unreliable packets. The other flags are automatically set by Genesis and should not be changed by the host application.

It is possible to broadcast a command packet to multiple remote hosts using the following methods in the IGenesisUDP interface:

int SendUnreliableCommandToAll(BroadcastFilter filter, 
                  byte flags, string opcode, string[] fields);
int SendReliableCommandToAll(BroadcastFilter filter, 
                  byte flags, string opcode, string[] fields);

These methods work exactly the same as the first two, except they take broadcast filter flags, which are defined in Constants.cs as:

[Flags]
public enum BroadcastFilter : int
{
    None     = 0,  //Filter out everything
    Servers  = 1,  //Send to servers we are connected to.
    Clients  = 2,  //Send to clients connected to us.
    All      = Servers | Clients,
                  //Send to both servers
                  //and clients (every connection).
    AuthedOnly = 4,//Only send to authed clients or servers we are authed with.
}

This allows the broadcast to be limited to servers, clients, and optionally only those connections that have successfully been authenticated.

Points of Interest

It is important to note that the events in Genesis are thrown on a separate thread - not the UI thread. This means that the Invoke method is needed to pass the event to the UI thread, if changing UI elements is your goal. The chat server uses this technique to change the UI based on event data.

When the StopListen method is called, Genesis automatically sends out a disconnection packet to all of the remote hosts connected to it to inform them that it is shutting down.

The only method within Genesis that can take a hostname instead of an IP is RequestConnect. All other methods need an explicit IP address.

History

  • v1.00 - Initial revision.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Rob Harwood
Web Developer
United Kingdom United Kingdom
Member
Born in England, I have been programming since a very early age when my dad gave me prewritten programs to type in and run on a Sinclair ZX81 machine (seeing my name printed out on a TV screen was enough to keep me entertained!). I later did work using basic and STOS basic on the Atari ST and after that got my first PC and used Microsoft's QBasic. Later when I was about 13 I was in an airport and saw a trial copy of Visual Basic on a magazine, which I bought and it got me hooked on the Microsoft development tools.
 
Currently I am studying a software engineering degree and have been working with .NET since 1.0. I have just moved over to Visual Studio 2005/.NET 2.0 and am loving it! During my degree I have worked for a year at DuPont, where I ended up changing a lot of their old existing software over to .NET and improving it in the process! Since then I have been back and done some consulting work involving maintaining some of their older C++/MFC software.
 
While most of my current interestes involve .NET I am also confident in working with C++ in Win32, VB, Java, and have even done some development work on the Linux platform (although most of this involved ensuring that software I wrote in C++ was platform independent).
 
I have a strong passion for software technology, both higher level and more recently, systems level stuff (the dissertation I am doing for my degree is to implement a small compiler and virtual machine in C# for a Pascal-style language).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionRejected by remoted host softwarememberbrightday8722 Apr '13 - 16:00 
Your article is great.
 
I used this core in my system: one service open udp port 27000 and about 80 clients connect to this frequently to send and receive "message". Everything seem ok but when clients login and logout too much (i do not know exactly the number), no client can connect to server, the message return is "Rejected by remoted host software", so I must restart the service.
 
Can you explain why i get this message (in your Events class) and how to solve it.
 
Thank you very much.
QuestionGenesis using Byte[] [modified]memberTopchris17 Jun '12 - 7:01 
I've played with this a ton of times before over the years, but I took about a year off of C# when I switched jobs to a java position.
 
So yesterday, to sharpen up my C# skills, I decided to have another look at Genesis and see what could be done with just playing with the basic library.
 
After a lot of debugging, I have a version that works seemingly perfectly, with methods passing byte[] OPcodes and IList(byte[]) fields, as opposed to strings and string[]s.
 
UPDATE: A lot of stuff looks like it can be updated in the library, for instance none of the methods in GenesisUDP use the Interfaces of Command or Connection objects, although they're clearly defined.
 
Another thing I'm doing is static methods to allow the Command objects to process themselves, and possibly a static Receiving threadpool that the ReceiveLoop() method will basically queue up packets for, the threadpool will then switch its processing based on the received OPCode.
Somehow this will have to be exposed to the implementer as well.

modified 18 Jun '12 - 8:16.

QuestionAutomatic disconnect from server or timeoutmembernandkishor209e4 Jun '12 - 2:42 
Automatic disconnect from server or timeout
GeneralGinesis Coremembereg gigo4 Nov '10 - 20:54 
Best Code ...
 
thank's.....
 
Thumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup:
GeneralFeatures DesiredmemberGary Noter22 Aug '10 - 5:37 
These are desired features which I am building:
 
- Ability to choose from a list of known users online and invite them to a private chat.
- In a private chat, ability to invite online users to chat
- In private chat, ability to disconnect selected user(s).
- In my list of online users, I'm using the checkboxlist control, this so the user doesn't need to 'remember' Control-click or Shift-Click to select users.
- Ability to record/log the chat (e.g. to file [.txt, .xml), database, etc.), which is needed in my case
- In a private chat, send to 1 or more users 'incognito'; e.g. that specific message is excluded from being recorded.
- In a private chat, ability for mgmt team member with appropriate security clearance to 'disengage' recording of chat, then reengage as needed.
 
I've updated the code with better exception handling in ASP.Net 2.0 (would love to use v3 or v3.5, but currently not an option).
 
I presently can't figure out how to disconnect a specific remote client (e.g. choosing their name from the list of users and specifically disconnecting that client, so I merely send a message to that specific client which, upon receipt of message, if it contains my disconnect param "within" the message, it disconnects from the server. I'm sure I'll figure out the better way soon.
 
I look forward to posting my modified solution, Genesis NG [Next Generation]), for others to consider. I'll hopefully be posting it by 15-Sept-2010; no promises, though!
ASPX ~ Apple Simply Performs eXcellently

NewsGreat AtriclememberChona117130 Jul '10 - 3:09 
U look a lot like adam sandler in your picture
 
Chona1171
Web Developer (C#), Silverlight

Generalgreat softwarememberMember 474330518 Mar '10 - 1:33 
very simple and understandable piece of code. thanks
Questioncan it be customize for private chat ?memberanil_mane17 Nov '09 - 3:34 
Do you have feature of private chat in this ?
and I think flash is also needs some work.
 

But overall project is excellent.
 
anil
anilmane@hotmail.com

Generalprogramming unblocking udp....memberraju475617 Sep '09 - 3:26 
hi
 
how to get the programme to be in a running state..
even with unblocking techniques using select()..
for instance using the code...
 
fd_set socks;
struct timeval t;
FD_ZERO(&socks);
//FD_SET(sock, &socks);
FD_SET(Recv_Socket, &socks);
t.tv_sec = timeoutinseconds;
if (select(Recv_Socket + 1, &socks, NULL, NULL, 0))
{
recvfrom(Recv_Socket, Recv_Buf, Recv_BufLen, 0, (struct sockaddr *) &Sender_Addr, &Sender_AddrSize);
} //with timeinterval set to 100 or 10;
 
the programm still hangs.. waiting for the incoming message... as we have other process running other than just recieving msg(like menu handling, etc..) i should be able to proceed with my execution even if there is no msg to be recieved.... (im still recieving the msg whenever the msg arrives..)....
GeneralRe: programming unblocking udp....memberraju475617 Sep '09 - 20:05 
ok ...
 
i got that trick..
 
just setting timeinterval to zero..... works fine.... Smile | :)
QuestionAny java and C++ code for genesis?memberPhil. Roy28 Jan '09 - 11:57 
Since I am in the middle of a project that is c# on one end and java on the other, are you aware of a port of Genesis that would have been made in other languages than C# while staying compatible with the other?
GeneralPrivate ChatroommemberShawn12815 Jun '08 - 5:16 
I just wondering how to add a private chat room to it?
 
Please advise!
Generaludp receiver problem when udp receiver is behind routermemberhafidz11 Feb '08 - 21:53 
LAN To LAN
i have 2 program which using udp technology for both send program and receive program.This two program work very well on LAN connection means both sender and receiver is in same connection.On lan setting i used port 11000 and ip is a fixed ip.
 
Lan to Outside world
But when i try it on the internet with same port for lan setting,sender is in private network(lan) and i try to send msg to receiver(outside world) where receiver is using dynamic ip address(behind router) it seems the destination pc cannot receive any message from the udp sender.
 
I'm sure there is no firewall blocking.i already tried winsock still cannot.i was not allowed to do NAT also not allowed to do DYNDNS. Anyone who have better solution please help me i'm working with this problem for 6 month
 
i'm using vb.net 2003
GeneralChat Conferencemembertempsh21 Aug '07 - 23:06 
Very nice article
Can this be used to send voice?
That is, I need to let many users connect to the server and hear the voice but only one user can speak at any time. I mean, each user can be put on a queue and speak for a few minutes and then the next user will speak.
Any idea is appreciated cause I really need to complete my project soon, though I'm beginner in this field Frown | :(
GeneralAsynchronous TCP library - similary designedmemberPetr Antos8 Jul '07 - 23:54 
Take a look at very similar project for TCP communication too; If you need short TCP roundtrips and maintain connection (sessions) between them, this is also handled by this thing:
http://www.codeproject.com/cs/internet/AsyncSocketServerandClien.asp[^]
 
I am using both of this libraries and I am very happy with them Smile | :)
 
Petr Antos

GeneralRUDP librarymembercdemez21 May '07 - 4:55 
cool article...
 
I even propose you to use the RUDP library : www.codeplex.com/RUDP
 
Wink | ;-)
 
Krys

QuestionMono?memberd_m_r17 May '07 - 7:28 
Does it work with Mono on Linux??
AnswerRe: Mono?memberPetr Antos8 Jul '07 - 23:44 
take a try Smile | :) , i have compiled this easily for Compact Framework with very few and easy changes
 
Petr Antos

Generalpleaseeememberchiro__farfousha30 Apr '07 - 14:31 
Please can you help me in my graduation project.
My project is to send a real video from a computer to a pocket PC.
I am just want to know the function that the server is knowing now that there is a client enter now to put in this function capturing video streaming to send it for client..
PLEASE can you reply for me. I wamt to know it now plssss
GeneralRe: pleaseeememberMember 474330518 Mar '10 - 1:37 
just read your thread, and i reckon your an idiot. period.
QuestionPeer-to-peer in single application?memberdanenglish29 Mar '07 - 10:23 
Great little UDP library, Rob!! I'm looking at your client/server example, but I was wondering about the best way to implement peer-to-peer in a single application where anyone can be the "server". Would I need two instances of Genesis in my app (one for client, one for server), or could a single instance handle it?
 
Thanks,
Dan English
Loud Dragon Games

Generalit doesn't work in netmemberdark_magician_625 Feb '07 - 22:09 
Nice work but it doesn't work in net.I allowed the UDP port and it still doesn't work in net. So i have found a code that works in net but i don't know where to put it. So please i need to know where to fix the problem with putting this code somewhere or how to fix the firewall (ZoneAlarm). My e-mail is d_magician_6@msn.com or jurko007@gmail.com
 
TcpListener listener;
IPAddress ipaAddress;
int iPort;
 
ipaAddress = IPAddress.Parse(ipAddress); ;
iPort=int.Parse(port);
 
IPEndPoint endPoint=new IPEndPoint (ipaAddress, iPort);
 
listener = new TcpListener (endPoint);
listener.Start();
QuestionGreat library! But sending byte arrays?memberRynus20 Nov '06 - 2:21 
Hey, first I want to say that your library works excellent. It's easy, and native C#. Great.
But I'm working on a freeware multiplayer game, and I need to send byte arrays (serialized objects). It seems that this isn't possible with your library, since your sending methods only allow string arrays :'(.
Is it possible, or easy to work around? Since converting a byte array to a string means loss of data (non-ascii chars).
 
-Yours, Rynus Rein
AnswerRe: Great library! But sending byte arrays?memberDragonD766018 Dec '06 - 19:44 
You can send byte[] as strings by just converting them. eg:
 
byte[] array;
string str;
str = System.Text.Encoding.Default.GetString(array);
 
on the other end...
array = System.Text.Encoding.Default.GetBytes(str);
 


 

-Dragon
GeneralRe: Great library! But sending byte arrays?memberRynus19 Dec '06 - 2:01 
I already tried that... But strange enough, some bytes aren't converted to a character, like a 1-byte or a 0-byte.
Questioncan work over the netmembermos66623 Jun '06 - 20:14 
could u make it work in wna instead of lan that would great for contact mostafa_mcsd2006@hotmail.comSmile | :) Smile | :)
AnswerRe: can work over the netmemberEric Engler5 Jul '06 - 6:59 
You just have to make sure your firewall will pass UDP traffic for the specified port. That should be all that's needed. This isn't something most companies would be interested in doing unless there's a business requirement for this kind of thing.
GeneralWire up events in vb.netmemberkuhiuhiu9 Jun '06 - 18:48 
Anyone know vb equivalent of c#:
 
m_UDP.OnConnectionAuth += new ConnectionAuthHandler(m_UDP_OnConnectionAuth);
 
I'm doing a request.connect, but the events never fire.... any ideas, here is what i'm using....
 
--------------------------------------------
Public m_UDP As GenesisCore.IGenesisUDP = GenesisCore.InterfaceFactory.CreateGenesisUDP("test")
 
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim server_ip As String = "10.10.12.99"
Dim server_req_id As String = ""
AddHandler m_UDP.OnConnectionStateChanged, New GenesisCore.ConnectionStateChangeHandler(AddressOf tt)
AddHandler m_UDP.OnConnectionRequestTimedOut, New GenesisCore.RequestTimedOutHandler(AddressOf jj)
Dim f As Integer = m_UDP.RequestConnect(server_ip, 10011, server_req_id)
End Sub
 
Sub tt(ByVal o As Object, ByVal e As GenesisCore.ConnectionStateChangeEventArgs)
MsgBox("t")
End Sub
Sub jj(ByVal o As Object, ByVal e As GenesisCore.RequestTimedOutEventArgs)
MsgBox("j")
End Sub
--------------------------------------------
 
Any ideas ?
Thanks.
Rob.
GeneralRe: Wire up events in vb.netmembereg gigo4 Nov '10 - 21:03 
use standard Instant VB...
to convert C# code to vb code
 
Work great for me.....
Questionit doesn,t workmembermos6664 Jun '06 - 15:03 
hi dear sir's i congratulate for this wonderful work but it works only on the lan how can i make it work on the net thanks scencerly yours
 
mos666_mcsd2006@hotmail.com
GeneralMAX_FIELD_LEN and MAX_FIELDSmemberTobias Hertkorn29 May '06 - 6:53 
Hi Rob,
 
first of all thanks for the great work!
 
I am having a bit of fun with your library and I just wondered if there are any limitations on MAX_FIELD_LEN and MAX_FIELDS in GenesisConsts. Why are they set to 2000 and 50? Performance reasons? Any reason not to set both to int.MaxValue. Big Grin | :-D Just kidding.
 
When constructing the message header it seems as if "only" short.MaxValue could be supported. Is there any reason not to set MAX_FIELD_LEN = short.MaxValue and MAX_FIELDS something like 500 (or short.MaxValue as well)? I know those values would allow for huge messages. But I would never hit both limitations simultaniously. For one specific message I need a lot of very short fields and for a different one only very few fields, but one of them might be quite big...
 
Thanks again!
 
Cheers,
Tobi
 
---
Tobi + C# = T#
GeneralRe: MAX_FIELD_LEN and MAX_FIELDSmemberDragonD766018 Dec '06 - 19:49 
The max field len and max fields are set like that so that you don't go over the max size of any packet. Genesis will send reliable commands as only one packet. Unreliable commands are just split up according to the max fields setting. to the best of my knowledge udp packets are limited to a packet size of 65535. but some routers and gateway may not like that. you can change them but do so wisely.
 

-dragon
QuestionBAN_CHECK_TIME?memberDragonD766028 May '06 - 19:04 
While looking through the source code i found BAN_CHECK_TIME. Which is not used anywhere! Any reason why?

 

-Dragon
Question.NET 1.1 ?memberkuhiuhiu22 May '06 - 15:51 
Hello,
 
I tried to add the assembly to a VS2003, however it doesn't work. Is there any easy way to allow Genesis to work with .NET 1.1 ?. Reason is that .Net 2.0 isn't installed here on our machines and adding that is beyond the scope of this project.
 
Thanks.
Bill.

AnswerRe: .NET 1.1 ?memberDragonD766027 May '06 - 13:42 
Just open up the source code and compile it with 1.1 then you will have a 1.1 assembly, Note: i have not tried this but it should work.
 
-dave
GeneralRe: .NET 1.1 ?memberkuhiuhiu8 Jun '06 - 3:30 
I recompiled with 1.1. I only needed to change 2 lines of code (DNS). Will test later... thanks.
 
Rob.
Generalref stringmemberOrionDR12 May '06 - 17:24 
what's the point of having a reference parameter for a reference type, such as a string?
GeneralRe: ref stringmemberRob Harwood13 May '06 - 0:19 
Run this program for your answer...
 
namespace StringTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string _str = "my string";
 
            changeme(_str);
            Console.WriteLine(_str);
            changemetoo(ref _str);
            Console.WriteLine(_str);
            Console.ReadKey( );
        }
 
        static void changeme(string s)
        {
            s = "changed by a";
        }
 
        static void changemetoo(ref string s)
        {
            s = "changed by b";
        }
    }
}

Questionmultiple element messagesmemberTim Bryan20 Mar '06 - 5:59 
Hi Rob,
 
I am enjoying learning about UDP network programming in part through your project. I am trying to send multiple element messages in the send array and can't seem to figure out the reason it doesn't make the trip. I am building the string array in the send click of your chat client like this.
string[] tipData = new string[11];
tipData[0] = Guid.NewGuid().ToString().ToUpper();
tipData[1] = "A5A0045876837592";
tipData[2] = "05";
tipData[3] = "22";
tipData[4] = "23.458756";
tipData[5] = "-114.4558394";
tipData[6] = "13-Mar-2006";
tipData[7] = "1043";
tipData[8] = "01";
tipData[9] = "Normal Tip";
tipData[10] = "Generated";
m_ServerConn.SendUnreliableCommand(0, "20", tipData);
 
I can step through your code and find the elements all get sized and added to the packet just fine. They are in the final send packet but don't come back in the receive loop. Only the first element containing the guid is received. Any ideas why this would be?
Thanks
 
Tim Bryan
Redmond, Oregon
AnswerRe: multiple element messagesmemberRynus14 May '06 - 7:11 
I think because you're sending more then 512 bytes of data?
QuestionCan Genesis UDP transfer Files?membermimipretty27 Jan '06 - 1:09 
Hi,Rob:Big Grin | :-D
Your great work has been amazing me .But I want to know seriously how to use your classes to transfer file in networking .
Roll eyes | :rolleyes:
 
Regards
zzz2010;P;):->Sleepy | :zzz:
 
why I exist ?
For creating myself!
Questionhow does peer-to-peer work..???memberdavidlars9915 Jan '06 - 12:59 
hi everyone,
 
I'm stuck! I need to understand how p2p application connects two private IP addresses to each other..? I'd really appreciate if someone can show me a right path here... Since this article is based on the network programming, I thought someone might drop in with some bright idea about it, or can explain a basic theory as to how p2p application would be implemented...
 
maybe you have to have at least one centralized server with public IP, which would chain up private IPs when they login to the server..?
 
thanks!
Dave
 

QuestionUsing asynchronous approach...memberdavidlars994 Jan '06 - 17:46 
Hi everyone,
 
I think this is a great article about UDP implementation, but as author has told me, "Socket.SendTo(...) limits you to send only 512-KB of data at a time, and I was wondering if it would make any difference if you use "Socket.BeginSendTo(...)" method? Rob, have you thought about it?
 
Cheers,
Dave
 

AnswerRe: Using asynchronous approach...memberRob Harwood5 Jan '06 - 1:36 
Dave,
 
Did you mean to say 512 bytes? I changed the MAX_COMMAND_LEN constant from 512 to 2048 to allow genesis to send datagrams up to 2Kb in size and it worked fine. As far as I know SendTo implies no such arbitary limit (and certainly did not seem to during my tests). I think you misunderstood what I told you before so I'll quote from an article I just found on about.com;
 
"The UDP datagram size is a simple count of the number of bytes contained in the header and data sections . Because the header length is a fixed size, this field essentially refers to the length of the variable-sized data portion (sometimes called the payload). The maximum size of a datagram varies depending on the operating environment. With a two-byte size field, the theoretical maximum size is 65535 bytes. However, some implementations of UDP restrict the datagram to a smaller number -- sometimes as low as 8192 bytes."
(http://compnetworking.about.com/od/networkprotocols/l/aa071200a.htm[^])
 
Despite the fact you can technically have 64Kb suze datagrams I would not recommend this as there is greater chance of datagram loss. I have also been told that many routers only support datagrams up to 8192 bytes. Genesis uses a maximum of 512 bytes to be super safe, although this limit may be changed easily using the MAX_COMMAND_LEN constant, so you could experiment with it easily.
 
The reason I did not use BeginSendTo/EndSendTo is because it gave no advantage over simply calling SendTo, which returns immediately anyway. Perhaps it would probably be necessary if the amount of data seing sent was substantially larger, which in turn would cause the SendTo call to stall for a while.
 
Regards,
 
Rob
QuestionRe: Using asynchronous approach...memberdavidlars995 Jan '06 - 12:13 
yeah, that makes sense. how about asynchronous approach, like using "Socket.BeginSendTo(...)" ? you said, it would be necessary if data being sent was larger, and even in this case, would it still require to create packets separately (like you do in your genesis chat) or it would split up large datagram by itself? if so, what does the recieving end have to worry about..?
 
I'm kinda trying to understand the whole thing, and that is why I keep asking these questions Confused | :confused: and I really appreciate everybody's feedback!
AnswerRe: Using asynchronous approach...memberRob Harwood5 Jan '06 - 14:26 
Yes, nothing would be done for you - you would still need to break up and parse the packets yourself.
 
No probs Smile | :) any more questions feel free to ask.
 
Regards,
 
Rob.
GeneralHelp availablememberRob Harwood21 Dec '05 - 7:50 
If you need help with implementing this project into an application then please let me know and I will happily attempt to help. You should be able to pick up most things from the chat demo project, and the rest from looking at the code, however that is a rather large assumption so I can't guarantee it Smile | :) .
 
Also, this is my first article here so if you see anything I've done wrong and could improve on please let me know, thanks.
 
- Rob
GeneralRe: Help availablememberchiro__farfousha17 Jun '07 - 10:10 
Good Evening Rob,
I am just wanna ask you about the project of Genesis UDP server and Client, I wanna use it in my graduation project but my project sends real time video communication from pc to a pocket pc through wireless connection. is It will be so difficult to add new function to send video in Genesis project or not ? and if you can help me to this because i stayed two months to do this and i dont know how to send video. if you can please answer me as soon as possible because my project must to be delivered after two weeks Thank you a lot for your time.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 21 Dec 2005
Article Copyright 2005 by Rob Harwood
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid