如何从服务器读取数据并将其发送到客户端?

How to read and send data to client from server?

我正在尝试使用我的电脑上的本地控制台服务器和 windows phone 8.1 上的客户端制作服务器客户端。我遇到的问题是我不知道如何从客户端读取传入的数据。我已经在互联网上搜索并阅读了一些微软教程,但它们没有解释如何读取服务器中的传入数据。这是我的。

客户端 windows phone 8.1:

private async void tryConnect()
{
    if (connected)
    {
        StatusLabel.Text = "Already connected";
        return;
    }
    try
    {
        // serverHostnameString = "127.0.0.1"
        // serverPort = "1330"
        StatusLabel.Text = "Trying to connect ...";
        serverHost = new HostName(serverHostnameString);
        // Try to connect to the 
        await clientSocket.ConnectAsync(serverHost, serverPort);
        connected = true;
        StatusLabel.Text = "Connection established" + Environment.NewLine;
    }
    catch (Exception exception)
    {
        // If this is an unknown status, 
        // it means that the error is fatal and retry will likely fail.
        if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
        {
            throw;
        }
        StatusLabel.Text = "Connect failed with error: " + exception.Message;
        // Could retry the connection, but for this simple example
        // just close the socket.

        closing = true;
        // the Close method is mapped to the C# Dispose
        clientSocket.Dispose();
        clientSocket = null;
    }
}

private async void sendData(string data)
{
    if (!connected)
    {
        StatusLabel.Text = "Must be connected to send!";
        return;
    }
    UInt32 len = 0; // Gets the UTF-8 string length.

    try
    {
        StatusLabel.Text = "Trying to send data ...";

        // add a newline to the text to send
        string sendData = "jo";
        DataWriter writer = new DataWriter(clientSocket.OutputStream);
        len = writer.MeasureString(sendData); // Gets the UTF-8 string length.

        // Call StoreAsync method to store the data to a backing stream
        await writer.StoreAsync();

        StatusLabel.Text = "Data was sent" + Environment.NewLine;

        // detach the stream and close it
        writer.DetachStream();
        writer.Dispose();
    }
    catch (Exception exception)
    {
        // If this is an unknown status, 
        // it means that the error is fatal and retry will likely fail.
        if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
        {
            throw;
        }

        StatusLabel.Text = "Send data or receive failed with error: " + exception.Message;
        // Could retry the connection, but for this simple example
        // just close the socket.

        closing = true;
        clientSocket.Dispose();
        clientSocket = null;
        connected = false;

    }
}

(来自 http://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj150599.aspx

和服务器:

public class Server
{
    private TcpClient incomingClient;

    public Server()
    {
        TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1330);
        listener.Start();

        Console.WriteLine("Waiting for connection...");
        while (true)
        {
            //AcceptTcpClient waits for a connection from the client
            incomingClient = listener.AcceptTcpClient();

            //start a new thread to handle this connection so we can go back to waiting for another client
            Thread thread = new Thread(HandleClientThread);
            thread.IsBackground = true;
            thread.Start(incomingClient);
        }
    }

    private void HandleClientThread(object obj)
    {
        TcpClient client = obj as TcpClient;

        Console.WriteLine("Connection found!");
        while (true)
        {
            //how to read and send data back?
        }
    }
}

到了服务器打印'Connection found!'的地步,但我不知道如何更进一步。

感谢任何帮助!

编辑:

现在我的 handleclientthread 方法如下所示:

private void HandleClientThread(object obj)
{
    TcpClient client = obj as TcpClient;
    netStream = client.GetStream();
    byte[] rcvBuffer = new byte[500]; // Receive buffer
    int bytesRcvd; // Received byte count
    int totalBytesEchoed = 0;
    Console.WriteLine("Connection found!");
    while (true)
    {
        while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0)
            {
                netStream.Write(rcvBuffer, 0, bytesRcvd);
                totalBytesEchoed += bytesRcvd;
            }
            Console.WriteLine(totalBytesEchoed);
    }
}

但它仍然没有将字节写入控制台

所以...在网上搜索了很多之后我找到了解决方案...

服务器:从服务器读取数据并将数据发送回phone:

   // method in a new thread, for each connection
    private void HandleClientThread(object obj)
    {
        TcpClient client = obj as TcpClient;
        netStream = client.GetStream();
        Console.WriteLine("Connection found!");

        while (true)
        {
            // read data
            byte[] buffer = new byte[1024];
            int totalRead = 0;
            do
            {
                int read = client.GetStream().Read(buffer, totalRead, buffer.Length - totalRead);
                totalRead += read;
            } while (client.GetStream().DataAvailable);

            string received = Encoding.ASCII.GetString(buffer, 0, totalRead);
            Console.WriteLine("\nResponse from client: {0}", received);

            // do some actions
            byte[] bytes = Encoding.ASCII.GetBytes(received);


            // send data back
            client.GetStream().WriteAsync(bytes, 0, bytes.Length);
        }
    }

Phone(客户端):从 phone 发送消息并从服务器读取消息:

 private async void sendData(string dataToSend)
 // import for AsBuffer(): using System.Runtime.InteropServices.WindowsRuntime;
    {
        if (!connected)
        {
            StatusLabel.Text = "Status: Must be connected to send!";
            return;
        }
        try
        {
            byte[] data = GetBytes(dataToSend);
            IBuffer buffer = data.AsBuffer();

            StatusLabel.Text = "Status: Trying to send data ...";
            await clientSocket.OutputStream.WriteAsync(buffer);

            StatusLabel.Text = "Status: Data was sent" + Environment.NewLine;
        }
        catch (Exception exception)
        {
            if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
            {
                throw;
            }

            StatusLabel.Text = "Status: Send data or receive failed with error: " + exception.Message;
            closing = true;
            clientSocket.Dispose();
            clientSocket = null;
            connected = false;
        }
        readData();
    }

    private async void readData()
    {
        StatusLabel.Text = "Trying to receive data ...";
        try
        {
            IBuffer buffer = new byte[1024].AsBuffer();
            await clientSocket.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial);
            byte[] result = buffer.ToArray();
            StatusLabel.Text = GetString(result);
        }
        catch (Exception exception)
        {
            if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
            {
                throw;
            }

            StatusLabel.Text = "Receive failed with error: " + exception.Message;
            closing = true;
            clientSocket.Dispose();
            clientSocket = null;
            connected = false;
        }
    }

我对 readData 方法中的 'await clientSocket.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial)' 命令非常不清楚。我不知道您必须创建一个新缓冲区,而 ReadAsync 方法会填充它(据我所知)。在这里找到它:StreamSocket.InputStreamOptions.ReadAsync hangs when using Wait()