【问题标题】:Connecting client and server on different networks using TCP使用 TCP 连接不同网络上的客户端和服务器
【发布时间】:2017-03-01 18:26:44
【问题描述】:

我正在尝试使用 TCP 将客户端连接到不同网络上的服务器(通过 Internet)、我朋友的 pc 上的客户端和我的服务器上,但我在客户端中获得了无效的 ip。 IP 是硬编码的,只是为了测试连接和发送内容的能力。

客户端代码:

class Client
{
    Socket clientSocket;
    byte[] buffer;

    public Client()
    {
        initializeClient();
    }

    private void initializeClient()
    {
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        buffer = Encoding.ASCII.GetBytes("hi server, i am a client");
        clientSocket.Connect(new IPAddress(Encoding.ASCII.GetBytes("156.205.***.**")), 100);
        //***.** altered by me to protect my IP but the ip is written complete in the code
        clientSocket.Send(buffer);
        clientSocket.Close();
    }
}

服务器代码:

class Server
{
    static byte[] buffer;
    static Socket serverSocket;
    static List<Socket> clientSockets;

    private void initializeServer()
    {
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        clientSockets = new List<Socket>();
        buffer = new byte[1024];
        serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));
        serverSocket.Listen(5);
        while (true)
        {
            Socket newClient = serverSocket.Accept();
            Console.WriteLine("new Client accepted: "+ newClient.RemoteEndPoint.ToString());
            Thread newThread = new Thread(new ParameterizedThreadStart(AcceptClients));
            newThread.Start(newClient);
        }
    }

    public Server()
    {
        initializeServer();
    }

    private void AcceptClients(object obj)
    {
        Socket client = (Socket)obj;
        clientSockets.Add(client);
        int recevied = client.Receive(buffer);
        Console.WriteLine("client said: " + Encoding.ASCII.GetString(buffer, 0, recevied));
        client.Close();
    }
}

【问题讨论】:

  • “但我在客户端获得了无效的 ip” - 请阅读 How to Ask 并发布包括您的研究在内的实际异常消息。您可能没有转发适当的端口。如何进行端口转发在网络上有很好的记录。
  • @CodeCaster 我通过使我的 ip 静态然后将端口 100 添加到我的路由器虚拟服务器来进行端口转发,但我仍然收到相同的错误:未处理的异常:System.ArgumentException:指定了无效的 IP 地址.参数名称:System.Net.IPAddress..ctor处的地址(Byte[] address)
  • 哦,是的,Encoding.ASCII.GetBytes("156.205.***.**") 行不通。您要么需要new byte[] { 156, 205, ...},要么直接致电IPAddress.Parse("156.205....")
  • @CodeCaster 是的,修复了它:) 谢谢

标签: c# sockets tcp network-programming client-server


【解决方案1】:

Encoding.ASCII.GetBytes("156.205.*.") 错误。它适用于 new byte[] { 156, 205, ...}

【讨论】:

    最近更新 更多