Click here to Skip to main content
15,891,567 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good time of day!

now faced with this problem. writing chat 1 on 1 in this case.

the problem is that that would take the message from the other all the time to listen to port.

but that's no problem to send out for it does not work
Here's the code runs in a separate thread
(Доброго время суток!

вот столкнулся с такой проблемой. пишу чат 1 на 1 в данном случае.

суть проблемы в том что что бы принять сообщение от другого нужно все время прослушивать порт.

но вот не задача отправить из за этого не получается
вот этот код запускается в отдельном потоке:)
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace kur_AIS_OOP_35
{
   public class SocketClient 
    {
        public static Boolean bSendMesg = true;
        public static Boolean bReadMesg = true;
        public static Boolean bExitProg = false;
        public static String ReadDATA = "000";
        public static String WriteDATA = "Вас приветствует клиент";

        IPHostEntry ipHost;
        IPAddress ipAddr;
        IPEndPoint ipEndPoint;
        Socket sender;
        string data = null;
       
        public SocketClient()
        {
            ipHost = Dns.Resolve("127.0.0.1");
            ipAddr = ipHost.AddressList[0];
            ipEndPoint = new IPEndPoint(ipAddr, 11000);
            
        }


        public static void ActionReadDATA(String data)
        {
            lock (ReadDATA)
            {
                ReadDATA = data;
            }
        }

        public void PostDataToClient()
        {
            
                byte[] msg = Encoding.UTF8.GetBytes(WriteDATA + "<theend>");
                int bytesSent = sender.Send(msg);
                bSendMesg = false;
            
        }

        public void GetDataToClient()
        {
            
            
            while (true)
            {
                //PostDataToClient();
                byte[] bytes = new byte[1024];

                int bytesRec = sender.Receive(bytes);
                if (bytesRec > 0)
                {
                    data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
                }
                else
                {
                    bReadMesg = false;
                    break;
                }
                //if (data.Length < iWTF) { bReadMesg = false; break; }
                if (data.IndexOf("<theend>") > -1) //конец сообщения
                {
                    bReadMesg = false;
                    break;
                }

                if (data.IndexOf("<theendsocket>") > -1) //конец соеденения
                {
                    bExitProg = true;
                    bReadMesg = false;
                    break;
                }
               
            }
            ActionReadDATA(data);
            data = "";
        }

        public void Client() 
        {
           
         while(true)
         {
             try
             {

                 sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                 sender.Connect(ipEndPoint);

                 ActionReadDATA("Сокет присоеденился к " + sender.RemoteEndPoint.ToString());
                 bReadMesg = false;

                 while (!bExitProg)//цикл для приема и передачи сообщений
                 {


                     if (bSendMesg)//посылаем
                     {

                         PostDataToClient();
                     }

                     if (bReadMesg)//принимаем
                     {
                         GetDataToClient();
                         

                     }

                 }
                 sender.Shutdown(SocketShutdown.Both);
                 sender.Close();
             }
             catch (Exception e)
             {
                 //  ActionReadDATA("Exception: " + e.ToString());
                 // bReadMesg = false; 
             }
             finally
             {
                 if (sender.Connected)
                 {
                     sender.Shutdown(SocketShutdown.Both);
                     sender.Close();
                 }
             }
         }
         } 
       } 

}
</theendsocket></theend></theend>

how can I fix it? is simply not enough forces ((((((((((((
(как же исправить? уже просто сил не хватает((((((((((( )
project file:
http://files.mail.ru/CG797O
Posted

1 solution

Yes, you need to listen to a port all the time. The "trick" is: you need to listen the way spending zero CPU time. The thread should call a blocking method which puts the thread in a special wait state; it is switched off by the OS and never scheduled back to execution until a connection comes from the client side.

Now, what is that kind of call? I use TcpListener.AcceptTcpClient(). Essentially, on the listening side you need two separate threads: one listening to the incoming connections (in cycle: when a client is accepted, its remote socket is added to you container of connected client, then the listener listens again, over and over; another one reads/writes from/to a network stream with all the connections so implementing your application-level protocol over TCP (in case of chat, this protocol is very simple, still am application-level protocol). You will need to use proper inter-thread synchronization primitives to work with share data, which is the shared container of clients.

You will need to use TcpClient and TcpListener classes; they do work on the level of sockets as you do, but on a bit higher level of abstraction. Your performance will not suffer at all.

Please see my past solutions where I sketch this design:
Multple clients from same port Number[^],
automatic updater triggered via server[^].

What I describe is the server side, however, you don't have to have purely client-server architecture with single passive threads and multiple active clients. Sometimes you need inversion of control, http://en.wikipedia.org/wiki/Inversion_of_control[^].

For better understanding, please read about pull and push technology, or server push:
http://en.wikipedia.org/wiki/Client%E2%80%93server_model[^],
http://en.wikipedia.org/wiki/Pull_technology[^],
http://en.wikipedia.org/wiki/Push_technology[^].

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900