【问题标题】:Why can't I get data from the server to the client?为什么我不能从服务器获取数据到客户端?
【发布时间】:2017-09-28 14:56:42
【问题描述】:

我从控制台向服务器发送文本,服务器将其发送给我。

        static void Main(string[] args)
    {
        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPEndPoint ipserv = new IPEndPoint(IPAddress.Parse("46.174.49.48"), 46666);
        client.Connect(ipserv);
        byte[] data = Encoding.UTF8.GetBytes(Console.ReadLine());
        client.Send(data);
        client.Receive(data); //here is the error
        Console.WriteLine(Encoding.UTF8.GetString(data));
        Console.ReadLine();
    }

错误:远程主机强行断开现有连接

服务器工作

【问题讨论】:

  • 您需要发布可以重现问题的代码。您需要为服务器提供代码,或者如果服务器属于第三方,请提供您尝试与之通信的服务器的一些详细信息

标签: c# networking server udp client


【解决方案1】:

您应该尝试使用 try-catch 语句以便更好地理解。由于以下一个或多个原因,它正在发生: 1)您正在向应用程序发送格式错误的数据或(2)客户端和服务器之间的网络链接由于某种原因而断开......(3)您在第三方应用程序中触发了一个错误,导致它会崩溃 (4)第三方应用程序已耗尽系统资源 可能我要说的第一个是数字 1。

示例:::

try {  
            sender.Connect(remoteEP);  

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

            // Encode the data string into a byte array.  
            byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");  

            // Send the data through the socket.  
            int bytesSent = sender.Send(msg);  

            // Receive the response from the remote device.  
            int bytesRec = sender.Receive(bytes);  
            Console.WriteLine("Echoed test = {0}",  
                Encoding.ASCII.GetString(bytes,0,bytesRec));  

            // Release the socket.  
            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());  
    }  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-30
    • 2020-08-16
    • 2015-09-30
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多