使用C#实现TCP客户端服务器应用程序

时间:2011-12-04 05:55:35

标签: c# sockets client-server

我正在尝试实现一个客户端服务器应用程序 服务器程序有一个计数器,根据请求递增1(没有提供给客户端的计数器值可以复制)
客户端程序要求服务器程序递增计数器并获得递增值
服务器程序应该能够一次处理多个客户端(至少5个) 计数器值应该由所有服务器线程共享,如果有的话


我已经在单独的项目中实现了服务器和客户端应用程序。当我开始运行服务器然后客户端时,服务器程序跟随行会产生NullReferanceException。

NetworkStream netstream = ((TcpClient)client).GetStream();

我是C#的新手。我想知道客户端如何连接到服务器并获得递增的值。 我在这里附上了我的代码。 提前致谢。

MyServer.cs

public abstract class MyServer
    {

        private static int port = 8080;
        private static TcpListener listener;
        private static Thread thread;
        private static int clientId = 0;

        static void Main(string[] args)
        {

            listener = new TcpListener(new IPAddress(new byte[] {127,0,0,1}),port);
            thread = new Thread(new ThreadStart(Listen));
            thread.Start();
        }


        private static void Listen()
        {
            listener.Start();
            Console.WriteLine("Listening on: " + port.ToString());

            while(true)
            {
                Console.WriteLine("Waiting for connection....");
                Console.WriteLine("Client No: " + clientId);
                TcpClient client = listener.AcceptTcpClient();
                Thread listenThread = new Thread(new ParameterizedThreadStart(ListenThread));
                listenThread.Start();
            }
        }

        private static void ListenThread(Object client)
        {

                NetworkStream netstream = ((TcpClient)client).GetStream();
                Console.WriteLine("Request made");
                clientId = clientId + 1;
                // String message = "Hello world";
                byte[] resMessage = Encoding.ASCII.GetBytes(clientId.ToString());
                netstream.Write(resMessage, 0, resMessage.Length);
                netstream.Close();


        }
    }

MyClient.cs

 class MyClient
    {
        static void Main(string[] args)
        {
            TcpClient tcpClient;
            int port = 8080;
            NetworkStream stream = null;

            tcpClient = new TcpClient("127.0.0.1", port);
            Console.WriteLine("Connection was established....");

            stream = tcpClient.GetStream();

            Byte[] response = new Byte[tcpClient.ReceiveBufferSize];
            stream.Read(response,0,(int)tcpClient.ReceiveBufferSize);

            String returnData = Encoding.UTF8.GetString(response);
            Console.WriteLine("Server Response " + returnData);

            tcpClient.Close();
            stream.Close();

        }
    }

1 个答案:

答案 0 :(得分:3)

你正在启动没有参数的线程,而它期望一个(客户端的TcpStream)。改变这个:

listenThread.Start();

到此:

listenThread.Start(client);

顺便说一句,我称之为clientThread而不是listenThread;线程没有收听,它正在关注客户端。