如何解决套接字连接的挂起问题?

问题描述:

这是我的服务器程序,它开始套接字连接:
但是,当我按开始连接时,程序挂起,直到接受客户端的连接,我如何按开始并与程序的另一部分一起使用?

this my server program that start socket connection :
but , when i press start connection , the program hang until , connection accepting form client , how can i press start and work with another section of program ?

private void button3_Click(object sender, EventArgs e)
 {
     byte[] data = new byte[100];
     IPAddress ip = IPAddress.Parse("192.168.0.100");
     IPEndPoint ipep = new IPEndPoint(ip, 8001);
     newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     newsock.Bind(ipep);
     newsock.Listen(1);
     client = newsock.Accept();
     IPEndPoint newclinet = (IPEndPoint)client.RemoteEndPoint;
     label2.Text = "Connected with  " + newclinet.Address + "   at port  " + newclinet.Port;
     string welcome = "Welcome goh to U.S.R.F wireless program";
     data = Encoding.ASCII.GetBytes(welcome);
     client.Send(data, data.Length, SocketFlags.None);

要么使用非阻塞形式,要么将侦听器分配给其他线程.
Either use a non-blocking form or assign the listener to a different thread.


使用异步套接字.
请参见此处 [
Use asynchronous sockets.
See here[^] for an example.