Click here to Skip to main content
15,887,928 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
my c# program get hang when it run . Can any one please tell me why

C#
private void button1_Click(object sender, EventArgs e)
        {
           
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.177"), 80);
            textBox2.Text = localEndPoint.ToString();
            try
            {
                sck.Connect(localEndPoint);
                byte[] bytes = new byte[25];
                 sck.Receive(bytes);//got hang here

               string myString = System.Text.Encoding.UTF8.GetString(bytes);

                
               textBox1.Text = myString+" a";
                sck.Close();
            }
            catch
            {
                Console.Write("Unable to Connect \r\n");
                textBox1.Text = "error";
            }
            
           
        }
Posted

It hangs because receive is a blocking call: if there is no data to receive then it waits. This is the reason why it is usually invoked in a separate thread.

[update]
Have a look at "Asynchronous Client Socket Example" at MSDN[^].
[/update]
 
Share this answer
 
v2
Comments
Savad.k.s 24-Nov-15 3:02am    
but i have a console application for this. its working fine and the out put is "ffffffff30" somthing like that
=======
console application sourcecode
======

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;

//client

namespace ConsoleApplication9
{
class Program
{
static Socket sck;
static void Main(string[] args)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.177"), 80);

try
{
sck.Connect(localEndPoint);
}
catch
{
Console.Write("Unable to Connect \r\n");
Main(args);
}
Console.Write("Enter Text: ");
string text=Console.ReadLine();
byte[] data = Encoding.ASCII.GetBytes(text);

sck.Send(data);
Console.Write("Data Sent!\r\n");
Console.Write("Press any key to Continue...");
string l;

Console.Read();

byte[] bytes = new byte[15];

sck.Receive(bytes);
Console.WriteLine(Encoding.UTF8.GetString(bytes));

sck.Close();
Console.Read();





}

}
}
You have to set the TimeOut properties for the socket connection because if you don't set a timeout the sockect keep waiting until data arrives and hangs your program execution.

The possible solution is using Async method.
Asynchronous Client Socket Connection[^]
GitHub Demo Project using Asynchronous Socket Client[^]
 
Share this answer
 

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