c#尝试socket连接后形成freez

时间:2015-08-30 03:13:20

标签: c# sockets

我创建了表单应用程序,并试图与socket进行聊天我的执行行" acc = sck.Accept();"形式freez和cant按任何按钮是什么形式,基本上,freez!什么影响错了?按教程做的

static Socket sck;
    static Socket acc;
    static int port = 9000;
    static IPAddress ip;
    static Thread rec;

private void button2_Click(object sender, EventArgs e){
            rec = new Thread(recV);

            ip = IPAddress.Parse(GetIp());
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sck.Bind(new IPEndPoint(ip, port));
            sck.Listen(0);
            acc = sck.Accept();

            /*while (true)
            {
                byte[] sdata = Encoding.ASCII.GetBytes("TEST");
                acc.Send(sdata, 0, sdata.Length, 0);
            }*/
        }

1 个答案:

答案 0 :(得分:0)

像这样使用AcceptAsync

private async void button2_Click(object sender, EventArgs e){
    rec = new Thread(recV);

    ip = IPAddress.Parse(GetIp());
    sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    sck.Bind(new IPEndPoint(ip, port));
    sck.Listen(0);
    acc = await sck.AcceptAsync();
    //This will block here, let the UI thread continue and then resume when a connection is accepted

    /*while (true)
    {
        byte[] sdata = Encoding.ASCII.GetBytes("TEST");
        acc.Send(sdata, 0, sdata.Length, 0);
    }*/
}

请注意,该方法现在为async,我正在使用await in front of the AcceptAsync`调用。

如果您希望发送/接收方法也释放用户界面,请查看相应的Async方法。