⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 p2papp.cs

📁 P2PGrid.rar 从网上下载的一套C#源码
💻 CS
字号:

using System;
using System.Threading;								// Sleeping
using System.Net;									// Used to local machine info
using System.Net.Sockets;							// Socket namespace
using System.Collections;
using System.Text;							// Access to the Array list

namespace P2PGrid
{
    /// <summary>
    /// Main class from which all objects are created
    /// </summary>
    class P2PApp : INetworkOperator
    {

        #region Fields
        //private IList clientList = new ArrayList();	// List of Client Connections
        private byte[] msgBuff = new byte[50];		// Receive data buffer
        private Socket serverSock;                  // Listening Socket 
        private Socket clientSock;                  // Client Socket
        private int[,] grid = new int[4, 4];

        #endregion

        public P2PApp()
        {
            for (int i = 0; i < 4; i++)
                for (int j = 0; j < 4; j++)
                    grid[i, j] = 0;


        }

        /// <summary>
        /// Close Client Socket
        /// </summary>
        public void CloseClient()
        {
            if (clientSock != null)
            {
                clientSock.Shutdown(SocketShutdown.Both);
            }          
        }

        public void CloseAll()
        {
            if (clientSock != null)
            {
                clientSock.Close();
            }      
            if (serverSock != null)
            {
                serverSock.Close();
            }
        }
        #region P2P Server Operation

        /// <summary>
        /// Start server for listening, setup callback for accept client
        /// </summary>
        /// <param name="port">server port</param>
        public void Start(int port)
        {
            // Create the listener socket in this machines IP address
           
            serverSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSock.Bind(new IPEndPoint(IPAddress.Loopback, port));	// For use with localhost 127.0.0.1
            serverSock.Listen(10);

            // Setup a callback to be notified of connection requests
            serverSock.BeginAccept(new AsyncCallback(OnConnectRequest), serverSock);

            Console.WriteLine("*** Grid Server {0} Started {1} *** ", port, DateTime.Now.ToString("G"));
        }
        /// <summary>
        /// Callback used when a client requests a connection. 
        /// Accpet the connection, adding it to our list and setup to 
        /// accept more connections.
        /// </summary>
        /// <param name="ar"></param>
        public void OnConnectRequest(IAsyncResult ar)
        {
            Socket listener = (Socket)ar.AsyncState;
            NewConnection(listener.EndAccept(ar));
            listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
        }

        /// <summary>
        /// Add the given connection to our list of clients
        /// Note we have a new friend
        /// Send a welcome to the new client
        /// Setup a callback to recieve data
        /// </summary>
        /// <param name="sockClient">Connection to keep</param>
        //public void NewConnection( TcpListener listener )
        public void NewConnection(Socket clientSock)
        {
            // Program blocks on Accept() until a client connects.
            // SocketChatClient client = new SocketChatClient( listener.AcceptSocket() );
            // SocketChatClient client = new SocketChatClient(sockClient);
            // m_aryClients.Add(client);
            Console.WriteLine("Client {0}, joined", clientSock.RemoteEndPoint);

            String connectedMsg = "Connected to " + clientSock.LocalEndPoint + "success \n\r";
            // Convert to byte array and send.
            Byte[] byteMsg = System.Text.Encoding.ASCII.GetBytes(connectedMsg.ToCharArray());
            clientSock.Send(byteMsg, byteMsg.Length, 0);

            SetupRecieveCallback(clientSock);
        }
        #endregion

        #region P2P Client Operation
        /// <summary>
        /// Callback used when a server accept a connection. 
        /// setup to receive message
        /// </summary>
        /// <param name="ar"></param>
        public void OnConnect(IAsyncResult ar)
        {
            // Socket was the passed in object
            Socket sock = (Socket)ar.AsyncState;

            // Check if we were sucessfull
            try
            {
                //sock.EndConnect( ar );
                if (sock.Connected)
                    SetupRecieveCallback(sock);
                else
                    Console.WriteLine("Unable to connect to remote machine", "Connect Failed!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message, "Unusual error during Connect!");
            }
        }

        /// <summary>
        /// Connect to the server, setup a callback to connect
        /// </summary>
        /// <param name="serverAdd">server ip address</param>
        /// <param name="port">port</param>
        public void Connect(string serverAdd, int port)
        {
            try
            {
                // Create the socket object
                clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // Define the Server address and port
                IPEndPoint epServer = new IPEndPoint(IPAddress.Parse(serverAdd), port);

                // Connect to server non-Blocking method
                clientSock.Blocking = false;
                
                // Setup a callback to be notified of connection success 
                clientSock.BeginConnect(epServer, new AsyncCallback(OnConnect), clientSock);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Server Connect failed!");
                Console.WriteLine(ex.Message);
            }
        }


        #endregion

        #region INetworkOperation Members

        public int GetGrid(int x, int y)
        {
            return grid[x, y];
        }

        public void SetGrid(int x, int y, int value)
        {
            grid[x, y] = value;
        }

        #endregion

        #region P2P Server&Client Operation

        /// <summary>
        /// Callback used when receive data., both for server or client
        /// Note: If not data was recieved the connection has probably died.
        /// </summary>
        /// <param name="ar"></param>
        public void OnRecievedData(IAsyncResult ar)
        {
            Socket sock = (Socket)ar.AsyncState;
            // Check if we got any data
            try
            {
                int nBytesRec = sock.EndReceive(ar);
                if (nBytesRec > 0)
                {
                    // Wrote the data to the List
                    string sRecieved = Encoding.ASCII.GetString(msgBuff, 0, nBytesRec);
                    ParseMessage(sock ,sRecieved);
                    //string msg = "(1,2)=3";
                    //Byte[] byteMsg = System.Text.Encoding.ASCII.GetBytes(msg.ToCharArray());
                    //sock.Send(byteMsg); 
                    // If the connection is still usable restablish the callback
                    SetupRecieveCallback(sock);
                }
                else
                {
                    // If no data was recieved then the connection is probably dead
                    Console.WriteLine("disconnect from server {0}", sock.RemoteEndPoint);
                    sock.Shutdown(SocketShutdown.Both);
                    sock.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message, "Unusual error druing Recieve!");
            }
        }

        public void Send(string msg)
        {
            Byte[] byteMsg = System.Text.Encoding.ASCII.GetBytes(msg.ToCharArray());
            clientSock.Send(byteMsg);
        }
        /// <summary>
        /// Setup the callback for recieved data and loss of conneciton
        /// </summary>
        /// <param name="app"></param>
        public void SetupRecieveCallback(Socket sock)
        {
            try
            {
                AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
                sock.BeginReceive(msgBuff, 0, msgBuff.Length, SocketFlags.None, recieveData, sock);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Recieve callback setup failed! {0}", ex.Message);
            }
        }  


        public void ParseMessage(Socket sock, string msg)
        {
            string[] messages = msg.Split(' ');
            int count = messages.Length;
            if (count > 0)
            {
                string first = messages[0].ToLower();
                if (first == "get" && (count == 3))
                {
                    string answer = GetGrid(int.Parse(messages[1]), int.Parse(messages[2])).ToString();
                    answer = string.Format("Grid [{0}][{1}] ={2}", messages[1], messages[2], answer);
                    Byte[] byteAnswer = System.Text.Encoding.ASCII.GetBytes(answer.ToCharArray());
                    sock.Send(byteAnswer);
                }
                else
                {
                    if (first == "set" && (count == 4))
                    {
                        SetGrid(int.Parse(messages[1]), int.Parse(messages[2]), int.Parse(messages[3]));
                    }
                    else
                    {
                        Console.WriteLine(msg);
                    }
                }
            }

        }
        #endregion
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -