使用TCP在不同网络上连接客户端和服务器

时间:2017-03-01 18:26:44

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

我正在尝试将客户端连接到不同网络(通过Internet)上的服务器,我朋友的PC上的客户端和使用TCP的服务器,但我在客户端获得无效的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();
    }
}

1 个答案:

答案 0 :(得分:1)

Encoding.ASCII.GetBytes(&#34; 156.205。 *。&#34;)错了。它适用于新的byte [] {156,205,...}