C#TCP客户端连接到服务器

时间:2019-01-24 11:01:35

标签: c# windows sockets networking tcp

我正在研究服务器和多个客户端之间的主从类型的网络关系。 服务器很好,问题是我是TCP新手,在客户端不知道ip形式开始的情况下,我不知道如何连接到服务器。

如果有人可以重写我的某些代码使其能够正常工作,我将很感激。

服务器

namespace Server
{
class Program
{
    static void Main(string[] args)
    {
        TcpListener listen = new TcpListener(IPAddress.Any, 8001);
        TcpClient clientSocket = default(TcpClient);
        int counter = 0;

        listen.Start();
        Console.WriteLine(" >> " + "Server Started");

        while (true)
        {
            counter += 1;
            clientSocket = listen.AcceptTcpClient();
            HandleClinet client = new HandleClinet();
            client.startClient(clientSocket, Convert.ToString(counter));
        }
    }
}

public class HandleClinet
{
    TcpClient clientSocket;
    string clNo;
    public void startClient(TcpClient inClientSocket, string clineNo)
    {
        clientSocket = inClientSocket;
        clNo = clineNo;
        Thread ClientThread = new Thread(DoChat);
        ClientThread.Start();
    }
    private void DoChat()
    {
        byte[] bytesFrom = new byte[1024];
        string dataFromClient = null;
        byte[] sendBytes = null;
        string serverResponse = null;

        while ((true))
        {
            try
            {
                NetworkStream networkStream = clientSocket.GetStream();

                networkStream.Read(bytesFrom, 0, 1024);
                dataFromClient = Encoding.ASCII.GetString(bytesFrom);
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
                Console.WriteLine(" >> " + "From client-" + clNo + " " + dataFromClient);

                serverResponse = Console.ReadLine();
                sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                networkStream.Write(sendBytes, 0, sendBytes.Length);

                networkStream.Flush();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}
}

客户

namespace Client
{
class Program
{
    public static TcpClient tcpclnt = new TcpClient();

    static void Main(string[] args)
    {
        while(true)
        {
            LoopConnect();
            LoopPacket();
            tcpclnt.Close();
        }
    }

    private static void LoopPacket()
    {
        byte[] bytesFrom = new byte[1024];
        string dataFromClient = null;
        byte[] sendBytes = null;
        string serverResponse = null;

        while ((true))
        {
            try
            {
                NetworkStream networkStream = tcpclnt.GetStream();

                serverResponse = "Give me a command!";
                sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                networkStream.Write(sendBytes, 0, sendBytes.Length);

                networkStream.Read(bytesFrom, 0, 1024);
                dataFromClient = Encoding.ASCII.GetString(bytesFrom);
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
                Console.WriteLine(" >> " + "From server -" + dataFromClient);
                networkStream.Flush();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }

    private static void LoopConnect()
    {
        Console.WriteLine("Connecting.....");
        while(true)
        {
            try
            {
                tcpclnt.Connect(IPAddress.Any, 8001); // The problem area
                break;
            }
            catch (Exception)
            {
                Console.Write(".");
            }
        }
        Console.WriteLine("Connected.");
    }
}
}

1 个答案:

答案 0 :(得分:0)

客户端应该以某种方式获取服务器的地址。该方法取决于网络类型(本地或Internet)。如果是互联网,没有已知的同行几乎是不可能的。如果是本地网络,则可以使用广播UDP请求(此方法取决于本地网络路由规则)。