已锁定 Asynchronous Socket Programming

  • 2012年4月15日 6:22
     
     

    I have to create an client-server application i.e. "network monitor" in which i created a asynchronous client and socket. In this application multiple clients  send screenshots to server and server will display all clients in matrics format. But I have received this error : after receiving some screenshots server will automatically closes connection and display error : : "WebDev.WebServer40.exe has stopped working".... Following is my code... Please help me to resolve this .....

    Server Code :

    using System;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    using System.Collections;
    using System.Threading;
    using System.IO;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Text;
    using System.Web;
    using System.Web.UI;


    public class serverSocket
    {   
        public AsyncCallback WorkerCallBack;
        private Socket mainSocket;
        ArrayList workerSocketList = ArrayList.Synchronized(new ArrayList()); 
        private int clientCount = 0;                                           
        private string ip_addr = null;
        private int imgCount = 0;
        
        public serverSocket()
        {
            ip_addr = getIP();
        }
        
        //
        //Listen Clients
        //
        public void ListenClients()
        {
            int portNo = System.Convert.ToInt32("8080");
            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, portNo);
            mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
            try
            {            
                mainSocket.Bind(ipLocal);                                                                    
                mainSocket.Listen(30);                                                                     
                mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);                          
            }
            catch (SocketException se)
            {
                MessageBox.Show("ListenClients:-" + se.Message);
            }
        }
       
        public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                Socket workerSocket = mainSocket.EndAccept(asyn);                  
                Interlocked.Increment(ref clientCount);                           
                workerSocketList.Add(workerSocket);                               
                string msg = "Welcome client " + clientCount;            
                SendMsgToClient(msg, clientCount);                                 
              
                WaitForData(workerSocket, clientCount);                            
                mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);  
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show("OnClientConnect:-"+se.Message);
            }
        }    
        
        //
        // Start waiting for data from the client
        //
        public void WaitForData(Socket sock, int clientNumber)
        {
            try
            {
                if (WorkerCallBack == null)
                {
                    WorkerCallBack = new AsyncCallback(OnDataReceived);
                }
                SocketPacket SockPkt = new SocketPacket(sock, clientNumber);
                sock.BeginReceive(SockPkt.dataBuffer, 0, SockPkt.dataBuffer.Length, SocketFlags.None, WorkerCallBack, SockPkt);
            }
            catch (SocketException se)
            {
                MessageBox.Show("WaitForData:-"+se.Message);
            }
        }

        //
        // This the call back function which will be invoked when the socket detects any client writing of data on the stream
        //
        public void OnDataReceived(IAsyncResult asyn)
        {
            SocketPacket socketData = (SocketPacket)asyn.AsyncState;
            try
            {
                int count = socketData.currentSocket.EndReceive(asyn);                     
                MemoryStream ms = new MemoryStream(socketData.dataBuffer);
                Image img = Image.FromStream(ms);

               
                string imgName = ((IPEndPoint)socketData.currentSocket.RemoteEndPoint).Address.ToString();    
                
                img.Save("K:/LAN Monitor/CaptureImages/" + imgName + ".jpg");
                imgCount += 1;

                WaitForData(socketData.currentSocket, socketData.clientNumber);           

            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                if (se.ErrorCode == 10054)                                                 
                {
                    MessageBox.Show("Client " + socketData.clientNumber + " Disconnected");
                    workerSocketList[socketData.clientNumber - 1] = null;                    
                }
                else
                {
                    MessageBox.Show("OnDataReceived:-"+se.Message);
                }
            }
        }

        public class SocketPacket
        {
            public Socket currentSocket;
            public int clientNumber;
            public byte[] dataBuffer = new byte[1024 * 2000];        

            public SocketPacket(Socket socket, int clientNo)  
            {
                this.currentSocket = socket;
                this.clientNumber = clientNo;
            }        
        }

        //
        //Send Data to all Clients
        //
        public void SendData(string msg, string ip)
        {
            try
            {  
                byte[] byData = System.Text.Encoding.ASCII.GetBytes(msg.ToString());
                Socket workerSocket = null;
                for (int i = 0; i < workerSocketList.Count; i++)
                {
                    workerSocket = (Socket)workerSocketList[i];
                    string ipAddr = ((IPEndPoint)workerSocket.RemoteEndPoint).Address.ToString();                
                    if (workerSocket != null)
                    {
                        if (ipAddr.Equals(ip))
                        {
                            if (workerSocket.Connected)
                            {
                                workerSocket.Send(byData);
                            }
                        }
                        else
                            MessageBox.Show("SendData: Error");
                    }
                }
            }
            catch (SocketException se)
            {
                MessageBox.Show("SendData:-" + se.Message);
            }
        }

        //
        //Send Data to Newly Connected CLient
        //
        public void SendMsgToClient(string msg, int clientNumber)
        {
            byte[] byData = System.Text.Encoding.ASCII.GetBytes(msg.ToString());         
            Socket workerSocket = (Socket)workerSocketList[clientNumber - 1];
            workerSocket.Send(byData);
        }

        //
        //Stop listening to Clients
        //
        public void StopListening()
        {        
            if (mainSocket != null)
            {
                mainSocket.Close();
            }
            Socket workerSocket = null;
            for (int i = 0; i < workerSocketList.Count; i++)
            {
                workerSocket = (Socket)workerSocketList[i];
                if (workerSocket != null)
                {
                    workerSocket.Close();
                    workerSocket = null;
                }
            }
        }

        //
        //Get local IP Address
        //
        String getIP()
        {
            String strHostName = Dns.GetHostName();
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName); 
            String IPStr = "";
            foreach (IPAddress ipaddress in iphostentry.AddressList) 
            {
                IPStr = ipaddress.ToString();
                return IPStr;
            }
            return IPStr;
        }
    }

    Client Code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.ComponentModel;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    using System.Windows.Forms;

    namespace Client_Soft
    {
        public class clientSocket
        {       
            IAsyncResult result;
            public AsyncCallback CallBack;
            public Socket clientSock;
            private string ip_addr="";
            byte[] dataBuffer = new byte[1024*20000];
            
            public clientSocket()
            {
                ip_addr = getIP();
            }

            //
            //Connect to Server...
            //
            public void ConnectToServer()
            {
                if (ip_addr == "")
                {
                    MessageBox.Show("IP Address is required to connect to the Server");
                    return;
                }
                try
                {
                    int portNo = System.Convert.ToInt32("8080");
                    clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
                    IPAddress ip = IPAddress.Parse(ip_addr);                                                    
                    IPEndPoint ipEnd = new IPEndPoint(ip, portNo);                                             
                    clientSock.Connect(ipEnd);                                                                 
                    if (clientSock.Connected)
                    {
                        WaitForData();                                                                         
                    }
                }
                catch (SocketException se)
                {
                    MessageBox.Show("ConnectToServer: " + se.Message);
                }
            }

            //
            //Waiting for data from Server
            //
            public void WaitForData()
            {
                try
                {
                    if (CallBack == null)
                    {
                        CallBack = new AsyncCallback(OnDataReceived);
                    }
                    SocketPacket SockPkt = new SocketPacket(clientSock);
                    result = clientSock.BeginReceive(SockPkt.dataBuffer, 0, SockPkt.dataBuffer.Length, SocketFlags.None, CallBack, SockPkt);
                }
                catch (Exception d)
                {
                    MessageBox.Show("WaitForData: " + d.Message);
                }
            }

            public class SocketPacket
            {
                public Socket thisSocket;
                public byte[] dataBuffer = new byte[1024 * 2000];

                public SocketPacket(Socket socket)
                {
                    this.thisSocket = socket;
                }
            }

            public void OnDataReceived(IAsyncResult asyn)
            {           
                try
                {
                    SocketPacket SockId = (SocketPacket)asyn.AsyncState;
                    int iRx = SockId.thisSocket.EndReceive(asyn);
                    char[] chars = new char[iRx + 1];
                    Decoder d = Encoding.UTF8.GetDecoder();
                    int charLen = d.GetChars(SockId.dataBuffer, 0, iRx, chars, 0);
                    String szData = new String(chars);
                    
                    if (szData.Contains("PerformAction"))
                    {
                        actions ac = new actions();
                        string str = szData.Substring(13);                    
                        ac.performAction(str);
                    }
                    else
                    {
                        MessageBox.Show(szData);
                    }

                    WaitForData();
                }
                catch (ObjectDisposedException)
                {
                    System.Diagnostics.Debugger.Log(0, "1", "OnDataReceived: Socket has been closed");
                }
                catch (Exception d)
                {
                    MessageBox.Show("OnDataReceived: " + d.Message);
                }
            }

            //
            //Send Data to Server
            //
            public void sendData(Bitmap b)  //here the bitmap is screenshot of client's screen
            {
                try
                {                
                    MemoryStream ms = new MemoryStream();                
                    b.Save(ms, ImageFormat.Jpeg);
                    byte[] byData = ms.GetBuffer();

                    if (clientSock != null)
                    {
                        clientSock.Send(byData);
                    }                
                    b.Dispose();
                    ms.Close();
                }
                catch (Exception d)
                {
                    MessageBox.Show("sendData: " + d.Message);
                }
            }

            //
            //Disconnect from Server
            //
            public void Disconnect()
            {
                if (clientSock != null)
                {
                    clientSock.Close();
                    clientSock = null;
                }
            }

            //
            //Get IP Address of local machine...
            //
            String getIP()
            {
                String hostName = Dns.GetHostName();
                IPHostEntry iphostentry = Dns.GetHostByName(hostName);             
                String ipAddr = "";
                foreach (IPAddress ipaddress in iphostentry.AddressList)   
                {
                    ipAddr = ipaddress.ToString();
                    return ipAddr;
                }
                return ipAddr;
            }
        }
    }

全部回复

  • 2012年4月17日 5:28
     
     

    Hi ganeshakshir,

    Welcome to the MSDN forum.

    You can consider posting it at the following more appropriate forum for more efficient responses. Thanks!

    .NET Framework Developer Center > .NET Development Forums > Network Class Library (System.Net)

    http://social.msdn.microsoft.com/Forums/en-US/ncl/threads


    Bob Shen [MSFT]
    MSDN Community Support | Feedback to us

  • 2012年4月30日 17:03
     
     
    Too much code to analyze, what is the InnerException or stack trace of the error seen?

    JP Cowboy Coders Unite!

  • 2012年4月30日 17:21
     
     

    You are using TCP connection.  Not sure why you are using sockets clas instead of TCPClient method, but that shouldn't make much difference.  Can you tell me how often your are sending message, the time between messages, and the approximate length of the messages.  TCP times out after a period of idle time and often doesn't come back up automatically like it is suppose to.  Some people set the times out to infinite to avoid this problem, but then is the server goes down you never come back up.

    To get more information on the state of the TCP connection you cna open a dos window and run the following command below on both the server and client.  Then look up the port number.  I would also recommand using a different port number than 8080 whihc is commonly used by other programs and may be busy.  Try a less common port number above 10,000 and see if you are having the same problems.

    Dos Command

    netstat -a


    jdweng