Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9133237
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T08:27:04+00:00 2026-06-17T08:27:04+00:00

I am making a chat service for a game, I am using a TCP

  • 0

I am making a chat service for a game,

I am using a TCP listener an client for the account information, some sort of login service. I’m wondering if i can keep the socked the client connected to the server with, to check if he is still online, and keep sending him messages if he has new messages.

I already tried making a list of sockets for the login queue, but it disconnected the previous socket to to server as soon as i accepted a new socket.

byte[] usernameByte = new byte[100];
int usernameRecieved = s.Receive(usernameByte);
//guiController.setText(System.DateTime.Now + " Recieved Login...");

byte[] passByte = new byte[100];
int passRecieved = s.Receive(passByte);
//guiController.setText(System.DateTime.Now + " Recieved Password...");

string username = "";
string password = "";

for (int i = 0; i < usernameRecieved; i++)
     username += (Convert.ToChar(usernameByte[i]));

for (int i = 0; i < passRecieved; i++)
     password += (Convert.ToChar(passByte[i]));

if (DomainController.getInstance().checkAccount(username, password))
{
    ASCIIEncoding asen = new ASCIIEncoding();
    s.Send(asen.GetBytes("true"));
    s.Send(asen.GetBytes("U are succesfully logged in, press enter to continue"));
    guiController.setText(serverName,System.DateTime.Now+"");
    guiController.setText(serverName, "Sent Acknowledgement - Logged in");
}
else
{
    ASCIIEncoding asen = new ASCIIEncoding();
    s.Send(asen.GetBytes("false"));
    s.Send(asen.GetBytes("U are NOT logged in, press enter to continue"));
    guiController.setText(serverName, System.DateTime.Now + "");
    guiController.setText(serverName, "\nSent Acknowledgement - Not logged in");
}

This is the code i currently use to check the account information the user send me. Right after i send this the user dropd the connection and i move on to the next one.

I have tried making 1 list of seperate sockets and processing them one by one, but that failed because the previous socket’s connection dropped, even tho it were 2 different machines that tried to connect.

Does anyone have a sollution / a way to save sockets, that I can use to make the program keep all the connections alive? so i can send a message from user 1 to user 2, and just use the socket they connected with? or do i need to add an id every time they make a connection?

EDIT

The client Code: (this is just a test client)

while (true)
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("xx.xxx.xxx.xx", 26862);
// use the ipaddress as in the server program

while(!(checkResponse(tcpclnt.GetStream())))
{
     Thread.Sleep(1000);
}

Console.WriteLine("Connected");

Console.Write("Enter the string to be transmitted : ");

String str = Console.ReadLine();
if (str == "")
{
    str = " ";
}
                    
Stream stm = tcpclnt.GetStream();

ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);


Console.WriteLine("Transmitting.....");

stm.Write(ba, 0, ba.Length);

Console.Write("Enter the string to be transmitted : ");

String str2 = Console.ReadLine();
if (str2 == "")
{
   str2 = " ";
}

Stream stm2 = tcpclnt.GetStream();

ASCIIEncoding asen2 = new ASCIIEncoding();
byte[] ba2 = asen2.GetBytes(str2);


Console.WriteLine("Transmitting.....");

stm.Write(ba2, 0, ba2.Length);
if (str == "false")
{
    blijvenWerken = false;
}
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);

for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));

byte[] bb2 = new byte[100];
int k2 = stm.Read(bb2, 0, 100);
Console.Write("\n");
for (int i = 0; i < k2; i++)
Console.Write(Convert.ToChar(bb2[i]));

Console.WriteLine("\n");

tcpclnt.Close();
Thread.Sleep(1000);
}

Server getting the sockets:
This bit of code is on the loginserver, its because i can only accept 1 socket every time to keep the connection alive, that i put queueCount on a maximum of 1.
I want to be able to make a list of Sockets that i accepted to add to a User account.

while (loginServerOn)
{
    if (queueCount < 1)
    {
        if (loginServer.getLoginListener().Pending())
        {
            loginQueue.Add(loginServer.getSocket());
            ASCIIEncoding asen = new ASCIIEncoding();
            Socket s = loginQueue.First();
            try
            {
                s.Send(asen.GetBytes("true"));
                queueCount++;
            }
            catch
            {
                loginQueue.Remove(s);
            }
        }
    }
}

The function that returns the accepted socket.

public Socket getSocket()
{
    return myList.AcceptSocket();
}

EDIT: Essence of the question

I want to add the socked or client recieved to my Account object, so every connection has an Account its linked to, when i want to send a message to a certain account, it should send a message to the socked or client bound to that account, can you help/show me how i can achieve this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T08:27:05+00:00Added an answer on June 17, 2026 at 8:27 am

    This is still c# and sockets but my approach is different to yours.

    I went with the concept of a “connectedCleint” which is similar in purpose to what you’ve called an account.

    I have a class called ServerTerminal which is responsible for accepting and top level management of socket connections. In this i’ve got:

     public Dictionary<long, ConnectedClient> DictConnectedClients =
            new Dictionary<long, ConnectedClient>();
    

    So this is my list of connected clients indexed by the sockethandle.

    To accept connections i’ve got a routine:

    public void StartListen(int port)
        {
            socketClosed = false;
            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
    
            listenSocket = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);
    
            //bind to local IP Address...
            //if ip address is allready being used write to log
            try
            {
                listenSocket.Bind(ipLocal);
            }
            catch (Exception excpt)
            {
                // Deal with this.. write your own log code here ?
                socketClosed = true;
    
                return;
            }
            //start listening...
    
            listenSocket.Listen(100); // Max 100 connections for my app
    
            // create the call back for any client connections...
            listenSocket.BeginAccept(new AsyncCallback(OnClientConnection), null);
    
        }
    

    So when a client connects it then fires off:

    private void OnClientConnection(IAsyncResult asyn)
        {
            if (socketClosed)
            {
                return;
            }
    
            try
            {
                Socket clientSocket = listenSocket.EndAccept(asyn);
    
                ConnectedClient connectedClient = new ConnectedClient(clientSocket, this, _ServerTerminalReceiveMode);
    
                //connectedClient.MessageReceived += OnMessageReceived;
                connectedClient.Disconnected += OnDisconnection;
                connectedClient.dbMessageReceived += OndbMessageReceived;
    
                connectedClient.ccSocketFaulted += ccSocketFaulted;
    
                connectedClient.StartListening();
    
                long key = clientSocket.Handle.ToInt64();
                if (DictConnectedClients.ContainsKey(connectedClient.SocketHandleInt64))
                {
                    // Already here - use your own error reporting..
                }
    
                lock (DictConnectedClients)
                {
                    DictConnectedClients[key] = connectedClient;
                }
    
                // create the call back for any client connections...
                listenSocket.BeginAccept(new AsyncCallback(OnClientConnection), null);
    
            }
            catch (ObjectDisposedException excpt)
            {
                // Your own code here..
            }
            catch (Exception excpt)
            {
                // Your own code here...
            }
    
        }
    

    The crucial part of this for you is:

                // create the call back for any client connections...
                listenSocket.BeginAccept(new AsyncCallback(OnClientConnection), null);
    

    This sets up the serverterminal to receive new connections.

    Edit:
    Cut down version of my connectedclient:

    public class ConnectedClient
    {
        private Socket mySocket;
        private SocketIO mySocketIO;
    
        private long _mySocketHandleInt64 = 0;
    
    
        // These events are pass through; ConnectedClient offers them but really
        // they are from SocketIO
    
        public event TCPTerminal_ConnectDel Connected
        {
            add
            {
                mySocketIO.Connected += value;
            }
            remove
            {
                mySocketIO.Connected -= value;
            }
        }
    
        public event TCPTerminal_DisconnectDel Disconnected
        {
            add
            {
                mySocketIO.Disconnected += value;
            }
            remove
            {
                mySocketIO.Disconnected -= value;
            }
        }
    
        // Own Events
    
        public event TCPTerminal_TxMessagePublished TxMessageReceived;
    
        public delegate void SocketFaulted(ConnectedClient cc);
        public event SocketFaulted ccSocketFaulted;
    
        private void OnTxMessageReceived(Socket socket, TxMessage myTxMessage)
        {
         // process your message
        }
    
    
    
        private void OnMessageSent(int MessageNumber, int MessageType)
        {
        // successful send, do what you want..
        }
    
    
    
    
    
        public ConnectedClient(Socket clientSocket, ServerTerminal ParentST)
        {
            Init(clientSocket, ParentST, ReceiveMode.Handler);
        }
    
        public ConnectedClient(Socket clientSocket, ServerTerminal ParentST, ReceiveMode RecMode)
        {
            Init(clientSocket, ParentST, RecMode);
        }
    
        private void Init(Socket clientSocket, ServerTerminal ParentST, ReceiveMode RecMode)
        {
            ParentServerTerminal = ParentST;
            _myReceiveMode = RecMode;
    
            _FirstConnected = DateTime.Now;
            mySocket = clientSocket;
            _mySocketHandleInt64 = mySocket.Handle.ToInt64();
            mySocketIO = new SocketIO(clientSocket, RecMode);
    
            // Register for events
            mySocketIO.TxMessageReceived += OnTxMessageReceived;
            mySocketIO.MessageSent += OnMessageSent;
            mySocketIO.dbMessageReceived += OndbMessageReceived;
    
        }
    
    
        public void StartListening()
        {
            mySocketIO.StartReceiving();
        }
    
        public void Close()
        {
            if (mySocketIO != null)
            {
                mySocketIO.Close();
                mySocketIO = null;
            }
    
            try
            {
                mySocket.Close();
            }
            catch
            {
                // We're closing.. don't worry about it
            }
        }
    
        public void SendMessage(int MessageNumber, int MessageType, string Message)
        {
            if (mySocket != null && mySocketIO != null)
            {
                try
                {
                    mySocketIO.SendMessage(MessageNumber, MessageType, Message);
                }
                catch
                {
                    // mySocketIO disposed inbetween check and call
                }
            }
            else
            {
                // Raise socket faulted event
                if (ccSocketFaulted != null)
                    ccSocketFaulted(this);
            }
        }
    
    
    }
    

    }

    Some useful links:

    This is where I started:
    http://vadmyst.blogspot.com.au/2008/01/how-to-transfer-fixed-sized-data-with.html

    http://vadmyst.blogspot.com.au/2008/03/part-2-how-to-transfer-fixed-sized-data.html

    And..

    C# Sockets and Multithreading

    Cause a connected socket to accept new messages right after .BeginReceive?

    http://nitoprograms.blogspot.com.au/2009/04/tcpip-net-sockets-faq.html

    http://www.codeproject.com/Articles/83102/C-SocketAsyncEventArgs-High-Performance-Socket-Cod

    I can’t post my entire solution just now; there is a flaw in my server code I need to debug; plus there are parts which my employer may not want published. But i based my code on what Vadym had for variable length messages.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am making a Chat server and client using tcp/ip in c. I made
can anyone please suggest some tutorials or APIs for making live chat applications in
I am making a chat application in android using TCP and has immplemented Sockets.
I'm making a chat responder for a game and i want know if there
I'm making a chat with a notification service. Sometimes that the notifications dont arrives
Im making a simple chat via Client/Server, and When I send the message to
I am making a chat client that receives structs of info from the server
I am making a java applet that has basic chat functionality (you can send/recieve
I'm making a simple client server chat application. I want to be able to
I'm making a simple cross platform chat program. I'm using wXWidgets for the GUI

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.