简体   繁体   中英

SocketAsyncEventArgs buffer filled with “System.Byte[]” instead of sent message

I recently started to develop a Windows Phone 7.1 application. The app requires a server to get answers from a database. For that I intend to use sockets and a tcp connection.

It worked really well connecting to the server but when I started to try streaming data the output was always "System.Byte[]". I thought that it simply must be some faulty cast from a byte[] to a string but it seems more complicated than that. The buffer is actually loaded with a byte[] of ASCII signs saying just "System.Byte[]". The message sent was "Bam!" in a byte[] of length 4. I don't know why this is but from what I have been able to gather it seems like the message sent simply is tinkered with during transmission or something. Please help me with this.

This is my code for the Windows Phone Client

public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();
    }
    private IPAddress ServerAddress = new IPAddress(0xff00ff00); //I sensored my IP
    private int ServerPort = 13000;
    private Socket CurrentSocket;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            ConnectToServer();
        }
        catch (Exception exception)
        {
            Dispatcher.BeginInvoke(() => MessageBox.Show("Error: " + exception.Message));
        }
    }

    private void ConnectToServer()
    {
        CurrentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        //Create a new SocketAsyncEventArgs
        SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs();
        socketEventArgs.RemoteEndPoint = new IPEndPoint(ServerAddress, ServerPort);
        socketEventArgs.Completed += ConnectionCompleted;

        socketEventArgs.SetBuffer(new byte[32], 0, 32);

        CurrentSocket.ConnectAsync(socketEventArgs);
    }

    private void ConnectionCompleted(object sender, SocketAsyncEventArgs e)
    {
        Dispatcher.BeginInvoke(() => MessageBox.Show("You are connected to the server"));

        //Create a new SocketAsyncEventArgs
        SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs();
        socketEventArgs.RemoteEndPoint = new IPEndPoint(ServerAddress, ServerPort);
        socketEventArgs.Completed += MessageReceived;

        socketEventArgs.SetBuffer(new byte[32], 0, 32);

        CurrentSocket.ReceiveAsync(socketEventArgs);
    }

    private void MessageReceived(object sender, SocketAsyncEventArgs e)
    {
        Dispatcher.BeginInvoke(() => MessageBox.Show("You have received a message!"));

        string message1 = Convert.ToString(e.Buffer);
        string message2 = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);

        if (message1.Equals(message2))
            Dispatcher.BeginInvoke(() => MessageBox.Show(message1));

        CurrentSocket.ReceiveAsync(e);
    }
}

This is the C# Server code

class ConnectionHandler
{
    TcpListener listener;

    public ConnectionHandler()
    {
        listener = new TcpListener(System.Net.IPAddress.Any, 13000);
        listener.Start();

        while (true)
        {
            Thread thread = new Thread(Service);
            Socket socket = listener.AcceptSocket();
            Console.WriteLine("Socket accepted");
            thread.Start(socket);
        }
    }

    public void Service(object arg)
    {
        Socket socket = (Socket)arg;

        try
        {
            Stream stream = new NetworkStream(socket);
            Console.WriteLine("Stream created");

            string output = "Bam!";

            Byte[] bytes = Encoding.UTF8.GetBytes(output);

            StreamWriter writer = new StreamWriter(stream);

            writer.Write(bytes);
            writer.Flush();
            writer.Close();

            output = Encoding.UTF8.GetString(bytes);

            Console.WriteLine("Message sent: " + output);

            stream.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("You got an error in ConnectionHandler");
            Console.WriteLine(e.Message);
            socket.Close();
        }

    }
}

The problem is in your Service method.

A StreamWriter allows you to write Unicode strings to an underlying Stream . It uses an Encoding to convert the strings to bytes before writing these to the Stream.

You're converting your string "Bam!" to bytes yourself and then call the StreamWriter.Write Method (Object) — the StreamWriter class doesn't have a Write method that accepts a byte[] .

The StreamWriter.Write Method (Object) invokes ToString on the passed object. And the ToString Method returns "String.Byte[]" for a byte[] .

Solution:

string output = "Bam!";

StreamWriter writer = new StreamWriter(stream);
writer.Write(output);
writer.Flush();
writer.Close();

or

string output = "Bam!";

Byte[] bytes = Encoding.UTF8.GetBytes(output);

stream.Write(bytes, 0, bytes.Length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM