简体   繁体   English

SocketAsyncEventArgs缓冲区填充为“ System.Byte []”,而不是已发送的消息

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

I recently started to develop a Windows Phone 7.1 application. 我最近开始开发Windows Phone 7.1应用程序。 The app requires a server to get answers from a database. 该应用程序需要服务器才能从数据库中获取答案。 For that I intend to use sockets and a tcp connection. 为此,我打算使用套接字和tcp连接。

It worked really well connecting to the server but when I started to try streaming data the output was always "System.Byte[]". 连接到服务器确实很好,但是当我开始尝试流式传输数据时,输出始终为“ 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. 我以为从byte []强制转换为字符串一定是错误的,但似乎比这复杂。 The buffer is actually loaded with a byte[] of ASCII signs saying just "System.Byte[]". 实际上,缓冲区中装有一个表示为“ System.Byte []”的ASCII符号的byte []。 The message sent was "Bam!" 发送的邮件是“ 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. 在长度为4的byte []中。我不知道为什么会这样,但是从我能够收集到的信息来看,似乎发送的消息只是在传输过程中被修补了。 Please help me with this. 请帮我解决一下这个。

This is my code for the Windows Phone Client 这是我的Windows Phone客户端代码

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 这是C#服务器代码

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. 问题出在您的Service方法中。

A StreamWriter allows you to write Unicode strings to an underlying Stream . StreamWriter允许您将Unicode字符串写入基础Stream It uses an Encoding to convert the strings to bytes before writing these to the Stream. 在将字符串写入流之前,它使用Encoding将字符串转换为字节。

You're converting your string "Bam!" 您正在转换字符串"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[] . 自己编写字节,然后调用StreamWriter.Write方法(对象)StreamWriter类没有接受byte[]的Write方法。

The StreamWriter.Write Method (Object) invokes ToString on the passed object. StreamWriter.Write方法(对象)在传递的对象上调用ToString And the ToString Method returns "String.Byte[]" for a byte[] . ToString方法返回"String.Byte[]"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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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