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

时间:2015-01-14 13:29:42

标签: c# sockets xaml windows-phone-8.1

我正在尝试使用我的电脑上的本地控制台服务器和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);
    }
}

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

1 个答案:

答案 0 :(得分:1)

所以...经过大量搜索互联网后,我找到了解决方案......

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

   // 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);
        }
    }

电话(客户端):从手机发送消息并从服务器读取消息:

 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()