繁体   English   中英

C# 聊天程序

[英]C# Chat Program

当我使用本地计算机托管并连接到它时,它可以 100% 工作,但是当我实时尝试时(服务器编程位于实际服务器上,客户端在其他计算机上)它不起作用。 我收到“无法建立连接,因为目标机器主动拒绝它”。 我检查了它是否在主动监听(并且服务器上的端口太正确)-它是禁用了所有防火墙,包括路由器[除了尝试禁用之外,它还有一个规则集允许它]-没有修复。

这可能是内部网络问题吗? 就像它只是不喜欢尝试连接到本地机器一样? 我一无所知,没有其他异常被抛出或任何东西。

服务器代码

IPAddress ip = IPAddress.Parse("127.0.0.1");
        Int32 port = 9818;
        TcpListener server = new TcpListener(ip,port);
        TcpClient client;try
        {
            server.Start();
            Console.WriteLine("Server Started..");


        }
        catch (Exception exp)
        {
            Console.WriteLine(exp.Message);

        }

        while (true)
        {
            client = server.AcceptTcpClient();

            byte[] recieveBuffer = new byte[100];
            byte[] sendBuffer = new byte[100];
            NetworkStream stream = client.GetStream();

            stream.Read(recieveBuffer, 0, recieveBuffer.Length);

            StringBuilder msg = new StringBuilder();
            foreach (byte b in recieveBuffer)
            {
                if (b.Equals(00))
                {
                    break;
                }
                else
                    msg.Append(Convert.ToChar(b).ToString());
            }

            int byteCount = Encoding.ASCII.GetByteCount(msg.ToString());
            byte[] sendData = new byte[byteCount];

            stream.Write(sendData, 0, sendData.Length);
            Console.WriteLine(msg);}//End while

而客户是..

public Int32 port = 9818;
    public TcpClient client;
    public string serverIP = "10.0.0.20";
    //public string serverIP = "localhost"; //For testings
    private void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            client = new TcpClient(serverIP, port);

            //Clean up space
            int byteCountU = Encoding.ASCII.GetByteCount(txtUser.Text);
            int byteCountP = Encoding.ASCII.GetByteCount(txtPassword.Text);

            //Send
            byte[] sendDataU = new byte[byteCountU];
            byte[] sendDataP = new byte[byteCountP];

            //Greating should be formated on server's end to not ruin user and password sending
            sendDataU = Encoding.ASCII.GetBytes(txtUser.Text);
            sendDataP = Encoding.ASCII.GetBytes(txtPassword.Text);

            NetworkStream stream = client.GetStream();

            stream.Write(sendDataU, 0, sendDataU.Length);

            //Close
            stream.Close();
            client.Close();

对不起,这个格式化界面是我能做的最好的

这是一个网络问题,而不是编程问题。

作为一般规则,网络类不关心另一端是否在同一台计算机、同一交换机或 Voyager 2 探测器上。 在那里开辟道路是一个网络问题,而不是编程问题。

我最好的猜测是 Windows Firefall 有点激进。

附带说明:异常处理是我的一个小烦恼,而您的则有问题。 这里有两篇关于我经常链接的主题的文章:

您将服务器设置为仅在 localhost (127.0.0.1) 上侦听。 这意味着只允许和解析本地连接,因此防火墙将在这些连接上禁用,您可以在大多数情况下忽略它。 当您调试应用程序或在同一台机器上进行进程间通信时,它很有用。

要监听来自其他机器的传入连接,您应该有足够的权限并将您的服务器地址设置为 0.0.0.0,即“监听所有外部连接”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM