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

本文关键字:客户端 服务器 读取 数据 | 更新日期: 2023-09-27 18:37:25

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

到了服务器打印"找到连接!"的地步,但我不知道如何进一步。

任何帮助不胜感激!

编辑:

现在我的句柄客户端线程方法如下所示:

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

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

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

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

服务器:

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

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

'await clientSocket.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial)'命令在readData方法中对我来说非常不清楚。我不知道你必须创建一个新的缓冲区,并且 ReadAsync 方法填充它(正如我所理解的那样)。在这里找到它:StreamSocket.InputStreamOptions.ReadAsync 在使用 Wait() 时挂起