用同步 socket 建立多线程 ,出现异常:通常每个套接字地址 (协议/网络地址/端口)只允许使用一次
因为异步 套接子 比较复杂,我就用了同步 套接字 ,在accept 后马上开启一个线程 ,代码如下:
public static void StartListening()
{
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
Console.WriteLine("localIPAddress is {0}",ipAddress.ToString());
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11090);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
//接受 连接产生新线程 监听端口
try
{
Thread thread = new Thread(new ThreadStart(StartListening));
thread.Start();
}
catch(Exception e ){
Console.WriteLine(e.ToString());
}
.....
}
可是他 提示我说:通常每个套接字地址 (协议/网络地址/端口)只允许使用一次。
应该怎样解决呢?