terça-feira, 28 de julho de 2015

Sockets Communications C#

Beware if you have intent to use Threat, is not for kids...

...
           Thread t = new Thread(listenClient);

            t.Start();
...
private void listenClient()
        {
            try
            {

                String strHostName = Dns.GetHostName();
                IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
                String ipAddress="";

                foreach (IPAddress add in ipEntry.AddressList) {
                   if (add.AddressFamily.ToString() == "InterNetwork")
                   {
                       ipAddress = add.ToString();
                       break;
                   }
                }

                IPAddress address = IPAddress.Parse(ipAddress);
                int port = 6666;
                TcpListener serverSocket = new TcpListener(address,port);
                TcpClient clientSocket = default(TcpClient);

                serverSocket.Start();

                while (true)
                {

                    clientSocket = serverSocket.AcceptTcpClient();
                    Client client = new Client();
                    client.startClient(clientSocket);
                }

                clientSocket.Close();
                serverSocket.Stop();
            }
            catch (Exception ex)
            {
                Logger.Instance.Log.Error("listenClient()" + ex.ToString());
            }
        }


     private void talk()
        {
            byte[] bytesFrom = new byte[10025];
            string dataFromClient = null;
            int dataSize = 0;

            networkStream = clientSocket.GetStream();

            try
            {
                while (true)
                {

                    try
                    {
                        dataSize = networkStream.Read(bytesFrom, 0, bytesFrom.Length);
                    }
                    catch(Exception ex){
                        return;
                    }

                    if (dataSize == 0)
                    {
                             ...
                        return;
                    }
                    else
                    {
                        dataFromClient = System.Text.Encoding.UTF8.GetString(bytesFrom);


                            ...

                        networkStream.Flush();
                    }

                }
            }
            catch (Exception ex)
            {
                Logger.Instance.Log.Error("talk ()" + ex.ToString());
                return;
            }

        }
Postar um comentário