socket程序得挂起C# [英] socket program get hangs C#

查看:144
本文介绍了socket程序得挂起C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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();
尝试
{
sck.Connect(localEndPoint);
byte [] bytes = new byte [ 25 ];
sck.Receive(bytes); // 挂在这里

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


textBox1.Text = myString + a;
sck.Close();
}
catch
{
Console.Write( 无法连接\\\\ n);
textBox1.Text = error;
}


}

解决方案

它因为 receive 是一个阻塞调用:如果没有要接收的数据,则等待。这就是为什么它通常在一个单独的线程中调用的原因。


[update]

有一个在MSDN上查看异步客户端套接字示例[ ^ ]。

[/ update]


您必须为套接字连接设置TimeOut属性,因为如果您没有设置超时sockect一直等待数据到达并挂起你的程序执行。



可能的解决方案是使用异步方法。

异步客户端套接字连接 [ ^ ]

Gi tHub使用异步套接字客户端演示项目 [ ^ ]

my c# program get hang when it run . Can any one please tell me why

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";
            }
            
           
        }

解决方案

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]


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[^]


这篇关于socket程序得挂起C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆