通过TCP发送具有多个客户端和一个服务器的对象

时间:2014-05-02 16:55:43

标签: c# sockets tcp

好的,我一直在环顾四周,找到了有关通过TCP发送自定义对象以及将多个客户端连接到一台服务器的教程,但是我无法找到两者的示例,所以决定尝试一下但是我被困住了。到目前为止,我已经编写了一个服务器,可以处理无限数量的客户端,但未能实现对象的发送。这是我到目前为止发送自定义对象的代码:

客户代码:

            Person p = new Person("Tyler", "Durden", 30); // create my serializable object
            string serverIp = "127.0.0.1";

            TcpClient client = new TcpClient(serverIp, 9050); // have my connection established with a Tcp Server

            IFormatter formatter = new BinaryFormatter(); // the formatter that will serialize my object on my stream

            NetworkStream strm = client.GetStream(); // the stream
            formatter.Serialize(strm, p); // the serialization process

            strm.Close();
            client.Close();

服务器代码:

        TcpListener server = new TcpListener(9050);
        server.Start();
        TcpClient client = server.AcceptTcpClient();
        NetworkStream strm = client.GetStream();
        IFormatter formatter = new BinaryFormatter();
        Person p = (Person)formatter.Deserialize(strm); // you have to cast the deserialized object

        strm.Close();
        client.Close();
        server.Stop();

这是我目前为多个客户提供的代码:

服务器代码:

private ArrayList m_aryClients = new ArrayList(); //List of connected clients (Used for threading)

    public Program()
    {
        //Empty constructor
    }

    static Program()
    {
    }

    #region Main Enty Point
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        //Set log file location
        setLogFileLocation("/usr/local/bin/ClipCloud/" + DateTime.Now.ToShortDateString() + ".log");
        //Start the application
        printAndLog("Starting server");
        Program appmain = new Program();
        //Get local hostname
        IPAddress[] addressList = null;
        string hostName = "";
        try
        {
            hostName = Dns.GetHostName();
            addressList = Dns.GetHostByName(hostName).AddressList;
        }
        catch (Exception ex)
        {
            printAndLog("Failed to get local address (" + ex.Message + ")", 1);
        }
        //Start listening and set up threads
        if ((addressList == null ? false : (int)addressList.Length >= 1))
        {
            object[] objArray = new object[] { "Listening on : (", hostName, ") ", addressList[0], ",", 399 };
            printAndLog(string.Concat(objArray), 0);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(new IPEndPoint(addressList[0], 399));
            socket.Listen(10);
            socket.BeginAccept(new AsyncCallback(appmain.OnConnectRequest), socket);
            //Wait until user types exit
            while (!(Console.ReadLine().ToLower() == "exit"))
            {}
            printAndLog("Shutting down server");
            socket.Close();
            //Clean up after yourself
            GC.Collect();
            GC.WaitForPendingFinalizers();
            printAndLog("Application successfully shutdown");
        }
        else
        {
            printAndLog("Unable to obtain local address" , 2);
        }
    }
    #endregion

    #region Server requests
    public void NewConnection(Socket sockClient)
    {
        //new client connected
        ClientHandler clientHandler = new ClientHandler(sockClient);
        m_aryClients.Add(clientHandler);
        printAndLog(string.Concat("Client (",clientHandler.Sock.RemoteEndPoint, ") connected"));
        //Send client welcome message
        DateTime now = DateTime.Now;
        string str = string.Concat("{", now.ToString("G"), "}");
        byte[] bytes = Encoding.ASCII.GetBytes(str.ToCharArray());
        clientHandler.Sock.Send(bytes, (int)bytes.Length, SocketFlags.None);
        clientHandler.SetupRecieveCallback(this);
    }

    public void OnConnectRequest(IAsyncResult ar)
    {
        try
        {
            Socket asyncState = (Socket)ar.AsyncState;
            NewConnection(asyncState.EndAccept(ar));
            asyncState.BeginAccept(new AsyncCallback(OnConnectRequest), asyncState);
        }
        catch (Exception ex)
        {
            printAndLog(ex.Message);
        }
    }

    public void OnRecievedData(IAsyncResult ar)
    {
        ClientHandler asyncState = (ClientHandler)ar.AsyncState;
        byte[] recievedData = asyncState.GetRecievedData(ar);
        if ((int)recievedData.Length >= 1)
        {
            foreach (ClientHandler mAryClient in this.m_aryClients)
            {
                try
                {
                    //This is where all data is sent out to all users!
                    mAryClient.Sock.Send(recievedData);
                }
                catch
                {
                    printAndLog(string.Concat("Failed to send data to client (", asyncState.Sock.RemoteEndPoint, ")"), 2);
                    mAryClient.Sock.Close();
                    this.m_aryClients.Remove(asyncState);
                    return;
                }
            }
            asyncState.SetupRecieveCallback(this);
        }
        else
        {
            printAndLog(string.Concat("Client (", asyncState.Sock.RemoteEndPoint, ") disconnected"), 0);
            asyncState.Sock.Close();
            this.m_aryClients.Remove(asyncState);
        }
    }
    #endregion
}
    internal class ClientHandler
{
    private Socket m_sock;

    private byte[] m_byBuff = new byte[50];

    public Socket Sock
    {
        get
        {
            return this.m_sock;
        }
    }

    public ClientHandler(Socket sock)
    {
        this.m_sock = sock;
    }

    public byte[] GetRecievedData(IAsyncResult ar)
    {
        int num = 0;
        try
        {
            num = this.m_sock.EndReceive(ar);
        }
        catch
        {
        }
        byte[] numArray = new byte[num];
        Array.Copy(this.m_byBuff, numArray, num);
        return numArray;
    }

    public void SetupRecieveCallback(Program app)
    {
        try
        {
            AsyncCallback asyncCallback = new AsyncCallback(app.OnRecievedData);
            this.m_sock.BeginReceive(this.m_byBuff, 0, (int)this.m_byBuff.Length, SocketFlags.None, asyncCallback, this);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Recieve callback setup failed! {0}", ex.Message);
        }
    }
}

有人可以帮我连接这两个。

0 个答案:

没有答案