c# - C#套接字编程错误

标签 c# sockets tcp udp client

你好,我试图建立一个连接两台电脑的连接。在本地代码中,下面的代码可以正常工作,但是当我们在另一台PC中启动客户端代码时,我们无法连接。代码如下。错误在哪里?

客户端:

void Start()
{
    Debug.Log(string.Format("Starting TCP and UDP clients on port {0}...", 90));
    udpThread = new Thread(new ThreadStart(ClientThread));
    udpThread.Start();

}

void ClientThread()
    {
        try
        {

            // Establish the remote endpoint  
            // for the socket. This example  
            // uses port 11111 on the local  
            // computer. 
            IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());

            string strHostName = "";
            strHostName = System.Net.Dns.GetHostName();

            IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);

            IPAddress addr = ipEntry.AddressList[0];
            IPAddress addr2 = ipEntry.AddressList[1];



            IPEndPoint localEndPoint = new IPEndPoint(addr, 90);

            // Creation TCP/IP Socket using  
            // Socket Class Costructor 
            Socket sender = new Socket(addr.AddressFamily,
                       SocketType.Stream, ProtocolType.Tcp);

            try
            {
                sender.Connect(localEndPoint);


                Console.WriteLine("Socket connected to -> {0} ",
                              sender.RemoteEndPoint.ToString());

                byte[] messageSent = Encoding.ASCII.GetBytes("Test Client<EOF>");
                int byteSent = sender.Send(messageSent);

                byte[] messageReceived = new byte[1024];

                int byteRecv = sender.Receive(messageReceived);
                Console.WriteLine("Message from Server -> {0}",
                      Encoding.ASCII.GetString(messageReceived,
                                                 0, byteRecv));

                sender.Shutdown(SocketShutdown.Both);
                sender.Close();
            }

            catch (ArgumentNullException ane)
            {

                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }

            catch (SocketException se)
            {

                Console.WriteLine("SocketException : {0}", se.ToString());
            }

            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }
        }

        catch (Exception e)
        {

            Console.WriteLine(e.ToString());
        }

    }

和服务器端
    private void Form1_Load(object sender, EventArgs e)
    {
        Console.WriteLine(string.Format("Starting TCP and UDP servers on port {0}...", port));

        devices_battery_midlow_pic_1.Visible = false;
        devices_battery_low_pic_1.Visible = false;
        devices_battery_midhigh_pic_1.Visible = false;
        devices_battery_high_pic_1.Visible = false;

        play_button.Anchor = (AnchorStyles.Bottom);

        Console.WriteLine(DateTime.Now.ToString() + " Getting IP...");
        IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        connection_id_label.Text = "This IP:\n" + ipAddress.MapToIPv4().ToString();

        Console.WriteLine(DateTime.Now.ToString() + " Starting Connection Thread...");

        connectionThread = new Thread(new ThreadStart(StartServer));
        connectionThread.IsBackground = true;
        connectionThread.Start();


    }
    private void StartServer()
    {
        string strHostName = "";
        strHostName = System.Net.Dns.GetHostName();

        IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);

        IPAddress addr = ipEntry.AddressList[0];

        Console.WriteLine(addr.MapToIPv4().ToString() + "  Starting Connection Thread...");

        IPEndPoint localEndPoint = new IPEndPoint(addr, 90);

        Socket listener = new Socket(addr.AddressFamily,
                     SocketType.Stream, ProtocolType.Tcp);

        try
        {
            listener.Bind(localEndPoint);

            listener.Listen(10);

            while (true)
            {

                Console.WriteLine("Waiting connection ... ");

                Socket clientSocket = listener.Accept();

                // Data buffer 
                byte[] bytes = new Byte[1024];
                string data = null;


                Console.WriteLine("Text received -> {0} ", data);
                byte[] message = Encoding.ASCII.GetBytes("Test Server");

                clientSocket.Send(message);

                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
        }

        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

可以在一台PC上运行,但是如果将服务器代码移到另一台PC上,我们将无法做出任何响应。错误在哪里?

最佳答案

客户端代码显式连接到同一台计算机上的服务器。而不是调用Dns.GetHostName(),您应该使用可配置值(例如命令行参数)或读取配置文件。

关于c# - C#套接字编程错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58952414/

相关文章:

mysql - 无法通过套接字 '/var/run/mysqld/mysqld.sock' 连接到本地 MySQL 服务器。

c#获取httponly cookie

c# - 无法将源类型 system.nullable 转换为目标类型 int

C# 相当于 Ruby 符号

c# - 如何从我的应用程序打开当前的 Excel 实例?

python - python中Socket.accept()的返回值是什么

android - 尝试读取 httpResponse 时套接字关闭异常

qt - 从以太网上的 Qt 应用程序发送文件

c - 如何识别用户空间和内核空间之间的特定套接字?

c# - Socket Keep-Alive 扩展如何工作? C#