1

I am using sockets for TCP-IP connection and I would like to establish simple system send-receive from the client side.

 Socket sck;
        sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint localEndpt = new IPEndPoint(IPAddress.Parse("123.123.123.1"), 12345);
        try
        {
            sck.Connect(localEndpt);
        }
        catch
        {
            Console.Write("Unable to Connect");
        }
        while (true)
        {
            Console.WriteLine("Enter Text");
            string sendtext = Console.ReadLine();
            byte[] Data = Encoding.ASCII.GetBytes(sendtext);
            sck.Send(Data);
            Console.WriteLine("Data Sent!");

            byte[] bytesReceived = new byte[sck.ReceiveBufferSize];
            int bytes = 0;
            String strReceived = "";

            int dataAvailable = 0;
            while (dataAvailable == 0 || dataAvailable != sck.Available)
            {
                dataAvailable = sck.Available;
                Thread.Sleep(100); // if no new data after 100ms assume transmission finished
            }

            if (sck.Available > 0)
            {
                bytes = sck.Receive(bytesReceived, bytesReceived.Length, 0);
                strReceived+=Encoding.ASCII.GetString(bytesReceived, 0, bytes);
            }

            Console.WriteLine("Received from server: " + strReceived);
        }
        Console.Read();

The problem is that first requests goes throught but the second does not, because socket is not available anymore (socket "Availabe" attribute value is 0). What am I doing wrong? What would be the easiest way to establish multiple send-recieve requests (in order)?

2 Answers 2

1

This code works fine for me

    private List<Socket> _clients = new List<Socket>();
    private Thread _dataReceiveThread;
    private bool _isConnected;

    private void DataReceive()
    {
        while (_isConnected)
        {
            List<Socket> clients = new List<Socket>(_clients);
            foreach (Socket client in clients)
            {
                try
                {
                    if (!client.Connected) continue;
                    string txt = "";
                    while (client.Available > 0)
                    {
                        byte[] bytes = new byte[client.ReceiveBufferSize];
                        int byteRec = client.Receive(bytes);
                        if (byteRec > 0)
                            txt += Encoding.UTF8.GetString(bytes, 0, byteRec);
                    }
                    if (!string.IsNullOrEmpty(txt))
                        /* TODO: access the text received with "txt" */
                }
                catch (Exception e)
                {
                    Exception_Handler(e);
                }
            }
        }
    }

Just run this code to get started

_isConnected = true;
_dataReceiveThread = new Thread(DataReceive);
_dataReceiveThread.Start();

Update list box in Cross thread:

This code can be placed in the comment section.

myListBox1.Invoke((Action)(() => { myListBox1.Items.Add(txt) }));
Sign up to request clarification or add additional context in comments.

Comments

1

Socket. Available does NOT indicate whether the socket is available, but incoming data is available for reading:
https://msdn.microsoft.com/en-us/library/ee425135.aspx

Your program quits because it checks for a reply (incoming data) immediately after sending a message out. Use a Thread.Sleep before checking for data.

Maybe the message has not even been sent, because Socket.Send just places it in the network interface card's output buffer. When the socket finally sends the message, it will upare the connection state. If it got no reply (on a TCP connection), it will tell you that it is disconnected when you query the state. On UDP it will tell you nothing, because UDP is connectionless.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.