Chat service application

2019-04-02 16:39发布

问题:

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:

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.



回答2:

When a server gets ready to accept TCP connections, it creates a new TCP socket, Bind() it to a port and uses the Listen() method. When a connection request comes in, the Listen() method returns a new socket that the server and client use for communication. The server and client can pass data back and forth using Send() and Receive() at this point. If the client disconnects, the server's Receive() terminates with 0 bytes of data.

If you want to wait for another connection request once you've accepted the first connection (i.e., while you are interacting with the first client) this can be done. At this point, you'll need to use something like threads or asynchronous methods so you can handle more than one connection. Basically, you will be able to Accept() connection requests from your listening socket.

Mike



标签: c# sockets tcp