Setting up a TCP/IP Client and Server to communicate over a network

前端 未结 2 656
梦谈多话
梦谈多话 2021-02-06 07:25

I am trying to learn a little about socket programming and I have stumbled across TcpListener and TcpClient to use as I read they are slightly easier for beginners. The basic ji

2条回答
  •  天涯浪人
    2021-02-06 08:00

    Not quite sure what you mean by 'more dynamic way to encompass the changing ip'. Taking a guess for starters where you currently have:

    TcpClient client = new TcpClient(, port); //Unsure of IP to use.
    

    You can run both client & server on the same machine and use the local loopback IP address:

    IPAddress.Parse("127.0.0.1")
    

    If they are running on different machines just replace 127.0.0.1 with whatever IP address the server is using (this assumes no NAT or firewalls in the way).

    If you don't want to use IP addresses you could always use hostnames (these might be considered more 'dynamic') but this would require a suitably configured DNS setup (for local systems):

    TcpClient client = new TcpClient("testMachine1", 1333);
    

    It's great to learn socket programming. I am the developer of a network library, networkcomms.net, so should you also want to work backwards from a work example at the same time as learning yourself please checkout this wpf chat example.

提交回复
热议问题