C#TCPListener问题

时间:2015-12-11 22:21:29

标签: c# tcplistener

我有以下代码来侦听计算机上localhost上的TCP / IP连接。当我运行应用程序(WPF应用程序)时,我收到以下错误消息。

感谢任何帮助。

谢谢。

更新代码:

try
{
    string sConnectionString = "Data Source=xxxx;Initial Catalog=xxxx;Integrated Security=false;User ID=xxxx;Password=xxxx";

    IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
    Console.WriteLine("Starting TCP listener...");

    TcpListener listener = new TcpListener(ipAddress, 13002);

    listener.Start();

    while (true)
    {
        Console.WriteLine("Server is listening on " + listener.LocalEndpoint);

        Socket client = listener.AcceptSocket();

        var childSocketThread = new Thread(() =>
        {
            byte[] data = new byte[100];
            int size = client.Receive(data);

            string incomingMess = " ";

            for (int i = 0; i < size; i++)
                incomingMess = incomingMess + Convert.ToChar(data[i]);

            Console.WriteLine("---> Message recorded in DB");
            Console.WriteLine(System.Environment.NewLine);

            SqlConnection con = new SqlConnection(sConnectionString);

            string regMess = "insert into Messages(incomingMessage) values(@incomingMessage_param)";
            SqlCommand regMessCommand = new SqlCommand(regMess, con);

            con.Open();
            regMessCommand.Parameters.AddWithValue("@incomingMessage_param", incomingMess);
            regMessCommand.ExecuteNonQuery();
            con.Close();

            client.Close();
        });
        childSocketThread.Start();
    }

    listener.Stop();
}
catch (Exception e)
{
    Console.WriteLine("Error: " + e.StackTrace);
    Console.ReadLine();
}

1 个答案:

答案 0 :(得分:0)

我希望您的程序先前已绑定到此端口,并且当您从循环中终止进程时端口尚未释放 - 如果您将端口号更改为13001/ 13002/13003 /其他随机,你觉得你还有例外吗?