C#RemoteEndPoint不存在

时间:2015-01-22 21:00:51

标签: c# tcp tcplistener

我在C#中创建一个简单的TCP服务器。它可以工作,我可以连接它,除了一件事,它说RemoteEndpoint不存在。我使用remoteendpoint获取客户端IP:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace tcpsockets
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener t = new TcpListener(IPAddress.Parse("0.0.0.0"),45123);
            t.Start();
            while (true)
            {
                Console.WriteLine("Waiting for a connection");
                TcpClient client = t.AcceptTcpClient();
                Console.WriteLine("Connection Recieved!");
                StreamReader sr = new StreamReader(client.GetStream());
                StreamWriter sw = new StreamWriter(client.GetStream());
                string text = sr.ReadLine();
                Console.WriteLine("text");
                IPEndPoint ipep = (IPEndPoint)t.RemoteEndpoint;
                IPAddress ipa = ipep.Address;
                Console.WriteLine(ipa.ToString());
                sw.WriteLine("Hello from the server");
                sw.Flush();
                client.Close();
            }
        }
    }
}

这是我的错误:

Error   1   'System.Net.Sockets.TcpListener' does not contain a definition for 'RemoteEndpoint' and no extension method 'RemoteEndpoint' accepting a first argument of type 'System.Net.Sockets.TcpListener' could be found (are you missing a using directive or an assembly reference?)   c:\users\logan\documents\visual studio 2013\Projects\tcpsockets\tcpsockets\Program.cs   27  49  tcpsockets

1 个答案:

答案 0 :(得分:2)

TcpListener确实没有RemoteEndPoint。您可能希望client.Client.RemoteEndPoint代替。

实际上,TCP侦听器的用途非常简单,仅限于接受新的客户端连接。一旦客户端被接受(建立新连接),听众就会忘记刚刚到达。所有进一步的通信都通过TcpClient实例(以及基础Socket - TcpClient.Client Property)进行。因此,您不应期望从侦听器获得远程端点的任何知识。