[C#] sockets

Newbie Spellweaver
Joined
Jun 14, 2009
Messages
8
Reaction score
0
I'm converting a java server to c# and I only have trouble with socket programming, it's not quite the same in c# as it is in java.

I need to do a few things:
Get the hostname of the user connecting (getInetAddress().getHostName() in java's serversocket)
Allow multiple connections (up to 300-500)

If I can get this working it would be so great, this is the only part of the project I have nearly no clue about. The rest I got down pretty well.

Just some basic code listening for clients and accepting clients (multiple?) would be epic.
 
Last edited:
Use TCPListener =)
I made a multi socket app on my laptop, I'll upload it when I'm at home.

May I ask what game you're converting?

-Kerelmans
 
Code:
shutdownClientHandler = false;
                clientListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientListener.Bind(new IPEndPoint(IPAddress.Any, ServerlistenerPort));
                clientListener.Listen(30);
                clientListener.BeginAccept(OnAccept, clientListener);

Code:
public void OnAccept(IAsyncResult e)
        {
            try
            {
                if (e.IsCompleted)
                {
                    Socket socket = clientListener.EndAccept(e);
                    socket.NoDelay = false;

                    String connectingHost = null;
                    if (!ConnectionHandler.floodProtection(connectingHost) &&
                        !ConnectionHandler.containsIp(connectingHost) &&
                        !ConnectionHandler.isIpBanned(connectingHost))
                    {
                        ConnectionHandler.addIp(connectingHost);
                        PlayerHandler.NewPlayerClient(socket, connectingHost);
                    }
                    else
                    {
                        socket.Close();
                    }
                }
            }
            catch (Exception ex)
            {

            }

            clientListener.BeginAccept(OnAccept, clientListener);
        }

Will this work for multiple clients? Also, how do I find the IP of the person who is connecting?
 
Last edited:
clientListener.Listen(30); <<<< that is the max number of connections it will allow.

You can use Socket.RemoteEndPoint() for getting the ip address and port of a connected user, I'm pretty sure those tutorials listed above should comment everything and should have everything you need. What are you moving over to C# anyway? OdinMS or something?
 
For those of you asking, it's a c# runescape private server being designed to be more stable than java runescape private servers.

It's all completed and everything it's just that, whenever I try starting it up, it loads everything up and then my internet kills itself.

My whole Server.cs file:

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Net.Sockets;
using System.Net;
using CSharpRSPServer.Server.Util;
using CSharpRSPServer.Server.Model.Players;
using CSharpRSPServer.Server.Model.NPCs;
using CSharpRSPServer.Server.Model.Items;
using CSharpRSPServer.Server.World;

namespace CSharpRSPServer.Server
{
    public class Server
    {
        public static Server clientHandler = null;
        public static Socket clientListener = null;
        public static Boolean shutdownServer = false;
        public static Boolean shutdownClientHandler;
        public static int ServerlistenerPort = 43594;
        public static ItemHandler itemHandler = new ItemHandler();
        public static PlayerHandler playerHandler = new PlayerHandler();
        public static NPCHandler npcHandler = new NPCHandler();
        public static ShopHandler shopHandler = new ShopHandler();
        public static ObjectHandler objectHandler = new ObjectHandler();

        public Server()
        {
            
        }

        public void KillServer()
        {
            try
            {
                shutdownClientHandler = true;
                if (clientListener != null)
                {
                    clientListener.Close();
                }

                clientListener = null;
            }
            catch (Exception __ex)
            {
                // error
            }
        }

        public void OnAccept(IAsyncResult e)
        {
            try
            {
                while (!e.IsCompleted)
                {
                    Thread.Sleep(500);
                }

                Socket socket = clientListener.EndAccept(e);
                socket.NoDelay = false;

                String connectingHost = socket.RemoteEndPoint.AddressFamily.ToString();
                if (!ConnectionHandler.floodProtection(connectingHost) &&
                    !ConnectionHandler.containsIp(connectingHost) &&
                    !ConnectionHandler.isIpBanned(connectingHost))
                {
                    ConnectionHandler.addIp(connectingHost);
                    //Misc.println("ClientHandler: Accepted from " + connectingHost + ":" + s.getPort());
                    playerHandler.newPlayerClient(socket, connectingHost);
                }
                else
                {
                    //Misc.println("ClientHandler: Rejected " + connectingHost + ":" + s.getPort());
                    socket.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            clientListener.BeginAccept(OnAccept, clientListener);
        }

        public void run()
        {
            try
            {
                shutdownClientHandler = false;
                clientListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientListener.Bind(new IPEndPoint(IPAddress.None, ServerlistenerPort));
                clientListener.Listen(Config.MAX_PLAYERS);
                clientListener.BeginAccept(OnAccept, clientListener);
                
                //Misc.println("Starting " + Config.SERVER_NAME + " on " + clientListener.getInetAddress().getHostAddress() + ":" + clientListener.getLocalPort());
                /*while (true)
                {
                    Socket s = clientListener.Accept();
                    s.NoDelay = false;
                    String connectingHost = s.RemoteEndPoint.AddressFamily.ToString();
                    if (!ConnectionHandler.floodProtection(connectingHost) &&
                        !ConnectionHandler.containsIp(connectingHost) &&
                        !ConnectionHandler.isIpBanned(connectingHost))
                    {
                        ConnectionHandler.addIp(connectingHost);
                        //Misc.println("ClientHandler: Accepted from " + connectingHost + ":" + s.getPort());
                        playerHandler.newPlayerClient(s, connectingHost);
                    }
                    else
                    {
                        //Misc.println("ClientHandler: Rejected " + connectingHost + ":" + s.getPort());
                        s.Close();
                    }
                }*/
            }
            catch (Exception ioe)
            {
                throw new Exception(ioe.Message);

                if (!shutdownClientHandler)
                {
                    //Misc.println("Error: Unable to startup listener on " + ServerlistenerPort + " - port already in use?");
                }
                else
                {
                    //Misc.println("ClientHandler was shut down.");
                }
            }
        }

        public void initialize()
        {
            ConnectionHandler.Initialize();
            try
            {
                Thread t = new Thread(run);
                t.Start();
            }
            catch
            {
                throw new Exception("t");
            }

            long lastTicks = Misc.CurrMillis();
            long totalTimeSpentProcessing = 0;
            int cycle = 0;

            while (!shutdownServer)
            {
                try
                {
                    itemHandler.process();
                    playerHandler.process();
                    npcHandler.process();
                    shopHandler.process();
                    objectHandler.process();
                }
                catch
                {
                    throw new Exception("t2");
                }

                long timeSpent = Misc.CurrMillis() - lastTicks;
                totalTimeSpentProcessing += timeSpent;
                if (timeSpent >= Config.CYCLE_TIME)
                {
                    timeSpent = Config.CYCLE_TIME;
                }

                try
                {
                    Thread.Sleep((int)(Config.CYCLE_TIME - timeSpent));
                }
                catch (Exception ex)
                {
                    
                }

                lastTicks = Misc.CurrMillis();
                cycle++;

                if (cycle % 100 == 0)
                {
                    float time = ((float)totalTimeSpentProcessing) / cycle;
                }
            }

            playerHandler.destruct();
            clientHandler.KillServer();
        }
    }
}

In my control panel's form:
Code:
            Server.Server s = new Server.Server();
            Thread t = new Thread(s.initialize);
            t.Start();

When the above code goes, it loads up and seems to work fine, I am not sure where it goes wrong, it seems to happen when I try to connect with a client... it kills my internet.
 
Dude, if you're reprogramming it in c#, don't just literally copy everyhing over. You'll have the same problems, with just a bit more speed. That source looks as identical to a java server... Make sopmething new. I personally am working on a c# server, and I am not even looking at the Java version. The point of using c# is to make it better, not make a copy that has the same problems. Using an async Socket is what I went with. TCPListener yeilded slightly slower results on my test machine
 
Dude, if you're reprogramming it in c#, don't just literally copy everyhing over. You'll have the same problems, with just a bit more speed. That source looks as identical to a java server... Make sopmething new. I personally am working on a c# server, and I am not even looking at the Java version. The point of using c# is to make it better, not make a copy that has the same problems. Using an async Socket is what I went with. TCPListener yeilded slightly slower results on my test machine

well i thought of doing that but instead i decided to convert an existing server and make it better which i have, going through the whole server taught me a ton about servers and how to fix existing glitches.

i am garbage at sockets in both languages, so i have no idea what to do with them, and the existing java one worked fine.

how can you say it looks like a java server? there's over 10 thousand different versions of a runescape private server out there. there isn't 10 thousand different ways to start up a server.
 
Back