C#服务器无法接收数据

时间:2016-03-23 12:22:35

标签: c# tcp tcpclient tcpserver

我正在用C#编写基本的TCP服务器/客户端,由于某种原因,我的服务器没有从客户端获取发送给它的数据。我无法弄清楚为什么会发生这种情况

    static void Main(string[] args)
    {
        Console.WriteLine("Server Started");
        int PORT = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Port"]);

        IPEndPoint ipep = new IPEndPoint(IPAddress.Any, PORT);
        Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        newsock.Bind(ipep);
        newsock.Listen(10);
        Socket client = newsock.Accept();
        while (true)
        {
            byte[] data = new byte[1024];
            int recv = client.Receive(data);
            if (recv == 0) break;
            string str = Encoding.ASCII.GetString(data, 0, recv);
            Console.WriteLine(str);
            data = Encoding.ASCII.GetBytes(str.ToUpper());
            client.Send(data, recv, SocketFlags.None);
        }
        client.Close();
        newsock.Close();
        Console.ReadLine();
    }

客户端看起来像这样:

        static void Main(string[] args)
    {
        Console.WriteLine("Starting Client");

        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80);
        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        try
        {
            server.Connect(ipep);
        }catch (SocketException e)
        {Console.WriteLine("Unable to connect to Server" + e.ToString());}


            while (true)
            {
            string input = Console.ReadLine();
            if (input == "exit") break;
            server.Send(Encoding.ASCII.GetBytes(input));
            Console.WriteLine("Sent");
            byte[] data = new byte[1024];
            int recv = server.Receive(data);
            Console.WriteLine("after client rec");
            string stringData = Encoding.ASCII.GetString(data, 0, recv);
            Console.WriteLine(stringData);
            }
            server.Shutdown(SocketShutdown.Both);
            server.Close();
        }
    }

0 个答案:

没有答案