How to read and send data to client from server?

user3122867

I'm trying to make a server client using a local console server on my pc and a client on windows phone 8.1. The problem that I have is that I don't know how to read the incoming data from the client. I've searched the internet and read serveral microsoft tutorials but they do not explain how to read the incoming data in the server. Here's what I have.

Client on 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;

    }
}

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

And the server:

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?
        }
    }
}

It comes to the point where the server prints 'Connection found!', but I don't know how to go further.

Any help is appreciated!

EDIT:

Now my handleclientthread method looks like this:

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

But it still doesn't write the bytes to the console

user3122867

So... after a lot of searching the internet I have found a solution...

Server: to read from the server and send data back to the 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(client): to send messages from the phone and read the messages from server:

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

The 'await clientSocket.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial)' command in the readData method was very unclear for me. I didn't know you had to make a new buffer, and the ReadAsync-method fills it(as i inderstand it). Found it here: StreamSocket.InputStreamOptions.ReadAsync hangs when using Wait()

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to send data from client to server in Meteor?

React and NodeJS: How can i send data from server to client?

How to send data(String) from HTTP client to server

How to send data from UDP Server to UDP client behind NAT?

How to send json data to client from node js server?

How to send multiple data streams from single client to a tcp server

How to send data from client socket to server socket using Python?

How do I send form data from the client side to the server

How to send continous data from server to client in Python?

send data from server to client nodejs

Send huge data from client to server

Java Send Data from server back to client

Send Continuous Data to Client from Server python

Java Sockets - send data from server to client

send data from java client to nodejs server

How to send client side data to server side

How to send data to a specific client on a multithreaded server

How to send a JPG file from server to client

How to send message from server to client

How to send messages from server to a specific client

How to record mic from client then send to server

how to send a picture from server to client in python

How to send pdf data and save from SQL Server using python(server) and Angular (client)

How to send data from client to raspberry pi?

how to read multiple lines from client to server

Vscode Language Client extension - how to send a message from the server to the client?

Problem with fetching/getting data from server TO client. (Send data from client TO server is working sucessfully)

How to send data from server-side (Express.js) to client-side (React.js)?

Angular2: How to send data from client to server when making request